pamiers
pamiers

Reputation: 355

I want to use index about randomly index in Java

I use Java. when I use ArrayList in Java. if I access index number randomly.

Is this posible?

If this is not posible. How should I do?

For example

ArrayList<String> al = new ArrayList<String>();
al.add(100,"stackoverflow");

Is this posible?

Upvotes: 3

Views: 198

Answers (4)

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382130

What you seem to need isn't an arrayList but a map between integers and strings :

HashMap<Integer,String> mymap = new HashMap<Integer,String>();

So you can write

mymap.put(100,"stackoverflow");

And

String myString = mymap.get(100);

Adding onto why you cannot use an arraylist:

When you first initialize an ArrayList, the size is zero. Attempting to add at an index that is larger than the size will still throw an IndexOutOfBounds exception just like an array would. The benefit of the ArrayList is that it will dynamically allocate more memory should the size fill up.

Besides, arrays aren't efficient for "sparse arrays" even if you make the effort to manage the size to avoid errors.

Upvotes: 6

amicngh
amicngh

Reputation: 7899

Is this posible?

Yes you can.Like below

   List<String> list=new ArrayList<String>();

    for(int i=0;i <10;i++)
    {
        list.add(i,new Integer(i).toString());
    }

    System.out.println(list.get(5));

If you want to use Random Number then you should generate number and you can add to that index.

Upvotes: 0

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33534

Ya... you can.. ArrayList gives lots of flexibility, like remove, add, indexOf..etc..

Eg:

ArrayList<String> arr = new ArrayList<String>();

arr.add("vivek");
arr.add("vicky");

arr.get(1);

Edited part:

If directly you try to add the element on the 100th when the size is less than that, you will get the following error:

java.lang.IndexOutOfBoundsException:

Upvotes: 0

giorashc
giorashc

Reputation: 13713

int index = (int)(Math.random() * myArray.size());
Object o = myArray.get(index);

Upvotes: 1

Related Questions