Hi All,

I have a question.

Is adding/filling range numbers to an ArrayList possible in java??

Like this:

{<12345, 13455>, <12745, 13755>, <2345, 2755>, <5345, 9455>, <2700, 5240>, <345, 13455>, 
<11345, 13000>}

You can think of these like time segments.

Here is the class to give you brief idea

import java.util.ArrayList;
import java.util.List;

class Sector  {
    int start;
    int end;

    public Sector(int start, int end) {
        this.start = start;
        this.end = end;
    }

    List<Sector> sectors = new ArrayList<Sector>(); 


    for (int i = 0; i <7; i++) {

    }
}
}

Recommended Answers

All 2 Replies

You could put the data in an array of arrays..

int[][] data = {{12345, 13455}, {12745, 13755}, etc

then use that to construct Sectors to add to the arraylist

17:       sectors.add(new Sector(data[i][0]. data[i][1]));

or have a Sector constructor that takes a two-element array, so it's just

17:       sectors.add(new Sector(data[i]);

You can use Arrays.asList:

List<Sector> sectors = Arrays.asList(
    new Sector(12345, 13455),
    new Sector(12745, 13755)
    /* etc. */
);

Note however that the returned List is not structurally modifiable [1], if you want to structurally modify (e.g. add, remove, insert sectors) the returned List later, then consider the following:

List<Sector> sectors = Arrays.asList(
    new Sector(12345, 13455),
    new Sector(12745, 13755)
    /* etc. */
);

sectors = new ArrayList<>(sectors);

Depending on your use case you might want to make Sector instances immutable, this has the advantage that you can pass them around everywhere without having to fear that their state will be mutated (changed).

Here's how you do that:

// An immutable Sector class
public class Sector
{
    private final int start;
    private final int end;

    public Sector(int start, int end)
    {
        this.start = start;
        this.end = end;
    }

    // ...
}

[1] A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification. (java.util.ArrayList)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.