【问题标题】:Java, add a value to list<pair>Java,向 list<pair> 添加一个值
【发布时间】:2016-03-26 18:28:34
【问题描述】:

我正在努力获取从 List&lt;Integer&gt;List&lt;Pair&lt;Integer,Integer&gt;&gt; 的值。 Pair是我写的一门课,我附上。 任何想法如何做到这一点?我宁愿做一个深拷贝,而不是只复制引用。我相信从列表中获取值可以正常工作,问题在于将此值插入到 listPair。

如有任何建议,我将不胜感激。

public class Pair<L,R>{
    private L key;
    private R value;


    public Pair(L key, R value)
    {
        this.key = key;
        this.value = value;
    }

    public L getL() {return key;}
    public R getR() {return value;}
    public void setL(L key) {this.key = key;}
    public void setR(R value) {this.value = value;}
}

It's how I create list(in main()) which I send to function createMatrix
List<Integer> numbersCopy = new ArrayList<Integer>();

    public static void createMatrix(List<Integer> list,List<List<Pair<Integer,Integer>>> matrix)
    {       
        Collections.sort(list); //sortuje listę
        Collections.reverse(list); //odwraca kolejnosc
        int key = 0;
        List<Pair<Integer,Integer>> listPair = new ArrayList<Pair<Integer,Integer>>();
        for(int i=0;i<list.size();i++)
        {
            listPair.setR(i) = list.get(i); //elements of list should be saved to value in Pair<Integer, Integer>
        }

}

【问题讨论】:

  • 试试:listPair.add(new Pair(i, list.get(i)))
  • 你预计这对组合的前半部分会是什么?当整数是不可变的时,为什么你认为你需要一个深拷贝?为什么你让你的 Pair 类是可变的?
  • 我想要一个深拷贝,因为我正在使用 list 中的值制作一个图表,我将删除并更改它们。我是 Java 新手,但如果我只复制引用,它会影响 list> 中的值。而且我不知道 Pair 类是可变的是什么意思。
  • 更重要的是我尝试了这两种方法,但它们都没有正常工作。使用 Titus 的 solutino 时,我收到 注意:czyGraficzny.java 使用未经检查或不安全的操作。注意:使用 -Xlint 重新编译:unchecked for details.
  • 为什么不用简单的地图呢? “对”列表(甚至没有相同的类型)只不过是一张地图(带有 Map.Entry 元素)。

标签: java list class collections insert


【解决方案1】:

将您的createMatrix 方法更改为以下

public static void createMatrix(List<Integer> list, List<List<Pair<Integer, Integer>>> matrix) {
    List<Integer> numbersCopy = new ArrayList<Integer>();

    Collections.sort(list); //sortuje listę
    Collections.reverse(list); //odwraca kolejnosc
    int key = 0;
    List<Pair<Integer,Integer>> listPair = new ArrayList<Pair<Integer,Integer>>();
    for(int i=0;i<list.size();i++)
    {
        listPair.add(new Pair<Integer, Integer>(i, list.get(i))); //elements of list should be saved to value in Pair<Integer, Integer>
    }
}

代码中的修改行为listPair.add(new Pair&lt;Integer, Integer&gt;(i, list.get(i)));

【讨论】:

    【解决方案2】:

    对我来说,Map.Entry&lt;K,V&gt; 是您寻找的实现,而不是您可以调用 put(K key, V value) 函数。

    https://docs.oracle.com/javase/7/docs/api/java/util/Map.html

    【讨论】:

      【解决方案3】:

      我认为更简单的是创建一个具有 2 个内部字段的 Bean 并将其作为

      class MyBean{
      Integer int0 =null;
      Integer int1 =null;
      }
      List<MyBean> datos = new List<MyBean>();
      

      【讨论】:

        猜你喜欢
        • 2021-11-05
        • 1970-01-01
        • 2015-09-27
        • 1970-01-01
        • 2021-09-15
        • 1970-01-01
        • 1970-01-01
        • 2022-01-02
        • 1970-01-01
        相关资源
        最近更新 更多