【问题标题】:How to access values of a list within a linked list?如何访问链表中的列表值?
【发布时间】:2012-08-05 22:29:31
【问题描述】:

我有一个链表,它存储一个类的对象,它有 4 个数据成员、2 个字符串、一个整数和另一个类的对象列表。

如何访问链表中的列表值?

好的,这就是我所拥有的

LogProcess lp=new LogProcess(revision,author,date,pathinfo,msg);

pathinfo 是 List 格式的列表。revision,author,date,msg 是字符串。

现在 PathInfo 是一个具有三个数据成员 action、kind、pathinfo 的类。所有 3 个都是字符串。

现在让我们说,如果我将链接列表传递给构造函数并想要访问 action、kind 和 pathinfo 的值,我该怎么办?

【问题讨论】:

  • 我认为快速查询(如“java 链表教程”)将回答您的问题。
  • 这个问题并不有趣,因为它可以通过谷歌搜索很快得到答案。
  • 请发布一些代码来支持您的描述。此外,请查看 Java 教程以了解如何使用标准集合。
  • 大家放松一下,帮助他重写问题,而不是投反对票。 @coder - 不清楚你卡在哪里

标签: java data-structures


【解决方案1】:

假设您使用的是LinkedList,您将调用get。如果你不使用泛型(LinkedList<YourFooObject> YourLinkedList; 会使用它们,LinkedList YourLinkedList 不会),那么你需要一个演员,像这样

 YourFooObject foo = (YourFooObject)YourLinkedList.get(0)

【讨论】:

  • 我不建议这样做,因为这是假设索引 0 中的项目是“YourFooObject”,您需要一个“instanceof”来验证其类型。我在下面发布了我的答案。
  • @coder - 这不是汉堡王。你的问题写得不好,如果你想要一个好的答案,问一个好问题。参见例如stackoverflow.com/questions/how-to-ask
【解决方案2】:
//Retriver one of the nodes of the linked list
YourObjectType node = yourLinkedList.get(int index)

//access the list instance variable of your object (depending on it visibility)
node.myList; //if accessible from here
MyList myList = node.getMyList();

【讨论】:

    【解决方案3】:

    LinkedList 的get(index) 函数将返回所需索引处的元素。

    YourStructure data = list.get(someindex);
    

    现在您可以从单个对象中获取列表:

    LinkedList<Something> sublist = data.getList();
    

    然后您可以像往常一样遍历该子列表:使用for 循环、foreachiterator

    【讨论】:

      【解决方案4】:

      在我看来,解决此问题的最佳方法是使用对象数组/列表/集合的 foreach 循环,例如:

      for(Object o : list) {
           if(o instanceof String) {
              //Object in list is a string
              String s = (String)o; //make sure to properly cast the object now that you know it is of proper type
           }
           else if(o instanceof int) {
              //object in list is an int
           }
           else if(o instanceof classA) {
              //object in list is from classA and you get the idea
           }
           else if(o instanceof classB) {
           }
      //etc..
      }
      

      【讨论】:

        【解决方案5】:

        您可以为您的 LinkedList 创建一个迭代器,以访问您的 LinkedList 的对象,即您的特定 class object,这样可以工作:

        LinkedList<YourObject> list = new LinkedList<YourObject>();
        ListIterator listIt = list.listIterator();
        YourObject sample = listIt.next();//or any of the objects you need in your list
        int valueOfSample = sample.getFirstParameter();//Assuming getFirstParameter is a method of your object class that returns the first integer parameter
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-08-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-10-13
          • 1970-01-01
          • 2018-09-05
          相关资源
          最近更新 更多