开发者

Java taking data from the wrong variable

I'm writing a short assignment involving generics. One of the methods is designed to replace an object in the generic set. I've posted the code below. I've fixed most of what's wrong, but the problem that persists is that Java is using the dat开发者_如何转开发a from newObject instead of theList.get(i). I put in output statements to test it, and whenever I asked it to print anything from theList, it instead gave me data from newObject. OldObject outputted information without a problem.

public boolean replaceObject(T oldObject, T newObject){
       if (theList.size()==0){
           System.out.println("The set is empty");
       }
       for (int i = 0; i < theList.size(); i++){
           if ((oldObject.toString().compareToIgnoreCase(theList.get(i).toString()))==0){
               theList.remove(i);
               theList.add(newObject);
               return true;
           }
       }
       return false;//executes if nothing found
   }

EDIT: Thanks for all of the responses, but the problem I'm concerned with is not that the search is skipping over entries, but rather that instead of searching through theList, it is only looking at newObject. theList.get(i) is NOT returning data from theList, the program is reading newObject and I don't know why.


I guess you want a replace operation: theList.set(i, newObject);.

EDIT: it's logic error: call remove() and add() in same loop.

Suppose the list=['a', 'b', 'c']:

In loop:

When i=0, list[0] is removed and 'd' is added, the list will be ['b', 'c', 'd'].

When i=1, 'b' is skipped!


When you remove an item from a list, all items below it come one step above to occupy a newer position.

for example - assume theList as follows:

index 0 --> a
index 1 --> b
index 2 --> c

for (int i = 0; i < theList.size(); i++) { }

// int i will be initially 0.

remove index 0 (removes a, but keeps the index, then b and c will move up )

after remove 0 ( because i == 0 )

index 0 --> b
index 1 --> c

add new item d (this will occupy the last index which is 2)

index 0 --> b
index 1 --> c
index 2 --> d //this is new.

now increment i ( i++ ) therefore i will be equal to 1,
then remove index 1 (because i is 1)

the list becomes

index 0 --> b
index 1 --> d
// notice that c is removed because that was at index 1. now d takes index 1

add new element e

index 0 --> b
index 1 --> d
index 2 --> e

and so on.

so every time you remove and add, you are not getting the right value, simply because ArrayList rearranges the index of the items.

Using "set", may not work, as it is used for replacing existing elements. It cannot be used to for adding new elements.

Option 1) A better option would be to use HashMaps. This would make sure you are removing the correct element. You will also be able to add new elements to the HashMap, with the appropriate key values.

Option 2) Instead of removing an element, set it as an empty String/Object. using "set". This way you are never changing the index.


Adding and removing to/from a list while iterating is playing with shap knifes:

   for (int i = 0; i < theList.size(); i++){
       if  ...
           theList.remove(i);
           theList.add(newObject);

The iterator gets out of sync.

Instead, you could use intermediate lists to store Objects to remove and add, and add and remove them in a final step: Sample, only removing:

public void remove (String name) 
{
    List <Person> blacklist = new ArrayList <Person> ();
    for (Person p : people) 
    {
        if (p.getName ().equals (name))
        {
            blacklist.add (p);
        }
    }
    people.removeAll (blacklist);
}


Everything worked fine for me. See to it that you are setting the list correctly.

Here is the simple sample code.

public class Test<T> {
public List<T> theList;

public Test()
{
    this.theList = new ArrayList<T>();
}

public boolean replaceObject(T oldObject, T newObject)
{
    if (theList.size() == 0) {
        System.out.println("The set is empty");
    }
    for (int i = 0; i < theList.size(); i++) {
        if ((oldObject.toString().compareToIgnoreCase(theList.get(i).toString())) == 0) {
            theList.remove(i);
            theList.add(newObject);
            return true;
        }
    }
    return false;//executes if nothing found
}

public static void main(String[] args)
{
    Test<String> t = new Test<String>();
    t.theList.add("ABC");
    t.theList.add("DEF");
    t.theList.add("GHI");
    System.out.println(t.replaceObject("DEF", "PQR"));
    System.out.println(t.theList.toString());

}}

The output comes as expected: true [ABC, GHI, PQR]

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜