使用 Java 中的最终值将 ArrayList 项添加到用户定义的类 [英] Adding ArrayList items to a user-defined class with final values in Java

查看:27
本文介绍了使用 Java 中的最终值将 ArrayList 项添加到用户定义的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含数千行数据的文本文件,如下所示:

I have a text file with thousands of lines of data like the following:

38.48,88.25
48.20,98.11
100.24,181.39
83.01,97.33

我可以很好地分隔每个双"值,但是我无法将每一行添加到我的用户定义类中.在我的主要方法中,我通过以下方式创建了一个列表:

I can separate each "double" value just fine, but I'm having trouble adding each line to my user-defined class. In my main method, I created a list by:

List<Pair> data = new ArrayList<Pair>();

其中对定义为:

class Pair {

  private final double first;
  private final double second;

  public Pair(double first, double second) {
    this.first = first;
    this.second = second;
  }

现在我正在尝试将项目添加到此列表中.我试过:"data.add(double, double)" 但这不起作用.我尝试在 Pair 类中创建一个 set 方法,但它不会让我因为第一"和第二"被声明为最终".我知道我可以改变它们,但我确实希望它们成为最终值.那么如何将项目添加到此列表中?

Now I'm trying to add items to this list. I tried: "data.add(double, double)" but that doesn't work. I tried creating a set method within the Pair class but it won't let me since "first" and "second" are declared as "final". I know I could just change them but I do want them to be final values. So how do I add an item to this list?

推荐答案

由于您已经将 List 声明为 List,所以需要添加 对象与该List 配对.您需要创建一个 Pair 的实例,将双精度值传递给它的构造函数,然后 add 将实例添加到 List 中.数据.像这样:

As you have declared the List as List<Pair>,you need to add Pair objects to that List. You need to create an instance of Pair passing the double values to its constructor and then add the instance to the List<Pair> data.Like this :

Pair pair = new Pair(doubleValue,doubleValue);
data.add(pair);

请仔细阅读List的文档,它为您提供了两个add方法来分别向List添加元素.

Please go through the documentation of List, it provides you two add methods to add elements to the List individually.

add(E e)add(int index,E e).

这篇关于使用 Java 中的最终值将 ArrayList 项添加到用户定义的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆