0

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?

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

This works! Thank you! Also, I had to change my "class Pair" to "static class Pair" to avoid complaints from the compiler.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.