开发者

how to define an arrayList with two columns in java?

I have a hashMap. Each "Value"is going to be a a list which will be mapped later on with my "Key"s. List is desired to look like this:

[length,time][length,time][length,time]

For example: Key{srcAddr=x, dstAddr=y, srcPort=12345, dstPort=80} value{(6523,0.001),(124,0.05), () , (), ...}

I just wonder how can I have a two-col arrayList.

package myclassifier;
import java.util.ArrayList;

public class FlowStatics {
int packetLength;
double timeArrival;
public FlowStatics(int pLength, double tArrival)
{
    this.packetLength = pLength;
    this.timeArrival = tArrival;


}

} and here is how I used it:

final ArrayList<FlowStatics> staticsArray = new ArrayList<FlowStatics>();
final HashMap<Flows, ArrayList> myHashMap = new HashMap<Flows, ArrayList>();

FlowStatics flowStatics = new FlowStatics(packetLength,timeArrival);
staticsArray.add(flowStatics);
myHashMap.put(flows, staticsArray);

and here is the part that I am reading it:

Iterator<Flows> iterator =  myHashMap.keySet().iterator();
while(iterator.hasNext()){
    Flows key = iterator.next();
    ArrayList value = myHashMap.get(k开发者_StackOverflowey);
    System.out.println("Fows"+key+"----------"+"Statics"+ value);


Well, your FlowStatics is the correct solution

List<FlowStatics> will give you the "two-column array list".

Update: as of your update, myHashMap.put(flows, flowStatics); is wrong. You are this putting an individual pair, rather than a list in the map. You should use:

staticsArray.add(flowStatics);
myHashMap.put(flows, staticsArray);


A List<E> is an abstraction for a homogeneous list of elements whose type is E. There are some restrictions (e.g. no primitives), but conceptually the type E can be defined to be whatever you want.

Suppose there's an abstraction of Pair<L,R>. Then a List<Pair<L,R>> is still a list of some E, but now that E is a Pair<L,R>. So it's still a "one-column" list, but each element in the list is a "pair", so it's sort of a "two-column" list.

Note that you don't always need a generic Pair<L,R>. Any type E that properly encapsulates all the information can be used in a List<E>.

And by the way, you can have a List<List<E>> too.

See also

  • Wikipedia/Encapsulation

Related questions

  • What is the equivalent of the C++ Pair<L,R> in Java?
  • List of Lists of Lists

Returning values analogy

Often people ask "How can I return two values in Java?". The answer is analogous. You return one value, a new type which encapsulates both information.

So instead of:

// attempt to return two values
// DOES NOT COMPILE

return "James Bond";
return "007";

You do:

return new SecretAgent("James Bond", "007");

Related questions

  • Using a java method to return multiple values?
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜