简体   繁体   中英

How to insert integers and strings in linked list? and how to search integers only from that list?

How to insert integers and strings in linked list? and how to search integers only from that list in java

Ok. To allow a List to store both Integers and Strings, you would need to use a list that operates on the common base class ie, Object.

List<Object> stringsAndNumbers = new ArrayList<Object>();

You can insert the objects into this List using the add method.

You can write a for-loop and traverse each of the entries using the get() method.

You can use instanceof operator to determine whether you are dealing with a String or an Integer.

http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html

Code it.

ArrayList<Object> al = new ArrayList<>();
al.add("mmm");
al.add(1);
al.add("ka");

for(Object a : al){
  if(a instanceof Integer){
   System.out.print(a); 
  }
}

Well its not good to have different type of objects in one collection. Though you can do it as -

List<Object> l = new LinkedList<Object>();
List<Integer> r = new LinkedList<Integer>();
l.add(new Integer(1));
l.add(new Integer(2));
l.add(new Integer(3));
l.add("a");
l.add("b");

System.out.println(l);

for(Object o: l) {
    if (o instanceof Integer) {
        r.add((Integer) o);
    }
}

System.out.println(r);

Are you talking about a Map that has a value of the int to retrieve the value of the string? such as:

     Map<Integer,String> myMap = new HashMap<Integer,String>();
     myMap.containsKey(myInteger)

Or do you mean to have them both types in a list if you want to then you can do something like this

     LinkedList<Object> myList = new LinkedList<Object>()

and then you can iterate on the linked list and check like this

  public void boolean findValue(LinkedList<Object> myList){
     for(Object myElement: ){
        if(myElement instanceof Integer && myElement == myValue){
           return true}
        }
     }
    return false
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM