Frage

Is it possible to create a Doubly Linked List in Java with two elements. One element has to be String where as the other one has to be Int.

Is this possible and if so How?

Thanks

War es hilfreich?

Lösung

LinkedList<Object> list = new LinkedList<Object>();
list.add(new String("Hello"));
list.add(new Integer(42));

EDIT: Updated according to OP's comments:

First create a class that will keep a String and an int:

public class ListNode {

   public String stringValue;

   public int integerValue;

   public ListNode(String s, int i) {
       this.stringValue = s;
       this.integerValue = i;
   }
}

Then add them to a LinkedList:

LinkedList<Object> list = new LinkedList<Object>();
list.add(new ListNode("Hello", 42));
list.add(new ListNode("Testing", 5));

Alternatively:

You can do it in a simpler way using an implementation of the Map interface (e.g. HashMap) and associate strings to integers like this:

Map<String, Integer> myMap = new HashMap<String, Integer>();
myMap.put("Hello", 42);
myMap.put("Testing", 5);
System.out.println(myMap.get("Hello")); // will print 42
System.out.println(myMap.get("Hello") + myMap.get("Testing")); // will print 47

Andere Tipps

LinkedList is doubly linked list implementation in java, You can have it for any object type wrapping your required fields

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top