Domanda

I want to retrive object in reverse insertion order.

For example i have collection object where i have inserted following object

mango apple orange

while retriving it should come in reverse insert order i.e orange,apple,mango and this collection class should now allow duplicate object also. Is there any inbuilt API is there in JDK 1.6 to do this?otherwise please tell me the logic to implement to do this.

È stato utile?

Soluzione 2

Here is a example for you. I hope this will help you.

public class ReverseCollection {

ArrayList<String> al = new ArrayList<String>();
    //add elements to the ArrayList

public static void main(String args[]){

    ReverseCollection rc = new ReverseCollection();

    rc.createList();
    System.out.println(" ------ simple order ---------");
    rc.print();
    Collections.reverse(rc.getAl());
    System.out.println(" ------ reverse order -------- ");
    rc.print();

}
private void print() {
    // TODO Auto-generated method stub
    for (int i = 0; i < al.size(); i++) {
        System.out.println(al.get(i));
    }
}
public ArrayList<String> getAl() {
    return al;
}
public void setAl(ArrayList<String> al) {
    this.al = al;
}
private void createList() {
    // TODO Auto-generated method stub
    al.add("JAVA");
    al.add("C++");
    al.add("PERL");
    al.add("PHP");
}

}

here I have used a inbuilt method of collectionc that is reverse Note that this method will change in original variable value.

Altri suggerimenti

Go for java.util.Stack which uses First in Last out policy. See docs for Stack

But read this too

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top