如何在链表中插入整数和字符串?以及如何仅从该列表中搜索整数?

时间:2015-11-03 12:11:48

标签: java

如何在链表中插入整数和字符串?以及如何仅从java中的列表中搜索整数

4 个答案:

答案 0 :(得分:1)

确定。要允许List存储整数和字符串,您需要使用在公共基类上操作的列表,即Object。

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

您可以使用add方法将对象插入此List。

您可以使用get()方法编写for循环并遍历每个条目。

您可以使用instanceof运算符来确定您是处理String还是Integer。

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

编码。

答案 1 :(得分:1)

{{1}}

答案 2 :(得分:0)

在一个集合中拥有不同类型的对象并不好。虽然你可以这样做 -

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);

答案 3 :(得分:0)

您是在谈论具有int值的Map来检索字符串的值吗?如:

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

或者你的意思是如果你愿意,可以将它们列在列表中 做这样的事

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

然后你可以迭代链表并像这样检查

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