May 2021 2 0 Report
Java compareTo() question.?

How do I use this method?

I'm using it like this to compare two objects:

if (key.compareTo(dictionary[numberOfEntries - i].getKey()) <= 0)

I think I'm doing something very wrong, because I am using this method to sort my generic objects, but it's not sorting correctly! I'm a bit frustrated, because I have no idea why this is failing on me.

for those of you who care, this is the code:

private int locateAddPlace(K key) {

int copyNE = numberOfEntries;

if (numberOfEntries > 0)

{

for (int i = 1; i <= numberOfEntries; i++)

{

if (key.compareTo(dictionary[numberOfEntries - i].getKey()) > 0)

return copyNE;

else if (key.compareTo(dictionary[numberOfEntries - i].getKey()) <= 0)

{

--copyNE;

}

}

}

return copyNE;

}

basically what I am doing is, I am trying to add something to a "dictionary". The dictionary works, but now I have to sort the entries I add into it. I am trying to use this method to find out exactly WHERE in my array, the newly added entry should be sorted. Yes, I am sorting as I am adding. This is my add method:

public V add(K key, V value) {

V oldValue = null;

int index;

index = locateIndex(key);

// we are adding a new [key:value] pair

if (index == -1) {

ensureCapacity();

Entry<K, V> newEntry = new Entry<K, V>(key,value);

int place = locateAddPlace(key); // finds out where the key should be.

int placeHolder = place;

if (place != (numberOfEntries))

{

for (int i = numberOfEntries; i > placeHolder; i--)

{

dictionary[i] = dictionary[i - 1];

}

dictionary[place] = newEntry;

}

else

dictionary[place] = newEntry;

numberOfEntries++;

NodeV newValue = new NodeV(value);

newValue.next = firstVNode;

firstVNode = newValue;

NodeK newKey = new NodeK(key);

newKey.next = firstKNode;

firstKNode = newKey;

}

else { // we are replacing an existing value

oldValue = getValue(key);

dictionary[index].setValue(value);

}

return oldValue;

} // end of add method.

Like I said, I have no idea why this isn't sorting. It makes sense to me.

Update:

oh sorry.

numberOfEntries, is the number of entries. starts at 0 by default, goes up by 1, each time a new entry is added.

dictionary is the name of the array. dictionary has it's own sub-class, which allows me to recall the "key", which is all I really need. dictionary holds a key and a value in each array unit. key is used to find the location of the dictionary, and the value is the information that needs to be recalled. :)

Please enter comments
Please enter your name.
Please enter the correct email address.
You must agree before submitting.

Answers & Comments


Helpful Social

Copyright © 2025 Q2A.ES - All rights reserved.