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

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

问题描述

我有成千上万像下面的数据行的文本文件:

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(双,双),但不起作用。我试图创建Pair类中的一组方法,但它不会让我,因为第一,第二被声明为最终。我知道我可以只改变他们,但我希望他们最终值。那么,如何将项目添加到这个列表?

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?

推荐答案

正如你所声明的列表列表&LT;对&GT; ,需要对象添加到列表。您需要创建传递双重价值给它的构造,然后实例添加实例给列表与LT;对GT&;数据。像这样的:

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

请通过列表的文件,它为您提供了两个添加方法元素添加到列表单独。

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

添加(E E)添加(INT指数,E E)

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

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