Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
116 views
in Technique[技术] by (71.8m points)

How to do union, intersect, difference and reverse data in java

I want to implement the union, intersect, difference and reverse operations in Java.

First I have 2 instances of ArrayList<Integer>

a = [0,2,4,5,6,8,10]
b = [5,6,7,8,9,10]

a union b should return c = [0,2,4,5,6,7,8,9,10]

a intersect b should return c = [5,8,10]

a difference b should return c = [0,2,4]

reverse a = [10,8,6,5,4,2,0]

Something like this.

How to implement that method in Java?


Update: I have to start with this template:

package IntSet;
import java.util.ArrayList;
import java.util.Collection;


public class IntSet {

private ArrayList<Integer> intset;

public IntSet(){
    intset = new ArrayList<Integer>();
}

public void insert(int x){
    intset.add(x);
}

public void remove(int x){
    //implement here
    intset.indexOf(x);
}

public boolean member(int x){
    //implement here
    return true;
}

public IntSet intersect(IntSet a){
    //implement here
    return a;
}

public IntSet union(IntSet a){
    //implement here
    return a;
}

public IntSet difference(IntSet a){
    //implement here
    IntSet b = new IntSet();
    return b; 
}
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First, the operations you describe (except reverse) are set operations, not list operations, so use HashSet or (if you need an ordering) TreeSet.

    Set<Integer> a = new TreeSet<Integer>(Arrays.asList(new Integer[]{0,2,4,5,6,8,10}));
    Set<Integer> b = new TreeSet<Integer>(Arrays.asList(new Integer[]{5,6,7,8,9,10}));

    //union
    Set<Integer> c = new TreeSet<Integer>(a);
    c.addAll(b);
    System.out.println(c);

    //intersection
    Set<Integer> d = new TreeSet<Integer>(a);
    d.retainAll(b);
    System.out.println(d);

    //difference
    Set<Integer> e = new TreeSet<Integer>(a);
    e.removeAll(b);
    System.out.println(e);

    //reverse
    List<Integer> list = new ArrayList<Integer>(a);
    java.util.Collections.reverse(list);
    System.out.println(list);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...