etho201
etho201

Reputation: 5

Adding ArrayList items to a user-defined class with final values in 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>();

Where Pair is defined as:

class Pair {

  private final double first;
  private final double second;

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

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?

Upvotes: 0

Views: 1862

Answers (2)

AllTooSir
AllTooSir

Reputation: 49402

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.

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

Upvotes: 4

Juned Ahsan
Juned Ahsan

Reputation: 68715

Adding to what Noob has mentioned. List or any other collection in java does not work on primitives. Collections store objects. So you need to create the object of your class pair, which will hold the details of first and second attribute. You can store multiple line of read file represented by Pair object in your list as:

List<Pair> data = new ArrayList<Pair>();
Pair pair = new Pair(first,second);
data.add(pair);

Upvotes: 0

Related Questions