Java Vector without re-ordering indices on remove, but leaving them null reusing those spaces on add command

StackOverflow https://stackoverflow.com/questions/21642660

Domanda

I want to avoid using plain arrays for this because I want something that has atleast the following commands

//grows in size if no null's are found.
key = indexOf(value);<br>
remove(key);<br>
add(value);<br>
contains(value);<br>
length(); //size();

Vector has all this except for the part of keeping the order of the indices in tact.

Maybe what I want already exists in Java SDK? Can someone tell me what it's called.

Code:

import java.util.Vector;

public class VectorDemo {

   public static void main(String[] args) {
      // create an empty Vector vec with an initial capacity of 4      
      Vector<Integer> vec = new Vector<Integer>(4);

      // use add() method to add elements in the vector
      vec.add(0,111);
      vec.add(1,9999);
      vec.add(2,191919);
      vec.add(3,-12394);

     System.out.println(vec);
     vec.remove(2);
     System.out.println(vec);

   }  
}

Output:

Executing the program....
$java -Xmx128M -Xms16M VectorDemo 
[111, 9999, 191919, -12394]
[111, 9999, -12394]

While I wanted this one output..

Output:

[111, 9999, 191919, -12394]
[111, 9999, null,   -12394]
È stato utile?

Soluzione

You can simply use

vec.set(2, null);

to reuse null elements on add you can do this

   int i = vec.indexOf(null)
   if (i == -1) {
        vec.add(obj);
   } else {
        vec.set(i, obj);
   }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top