I have a homework assignment where I need to insert or add new elemment into ArrayList<Interger>
with follow condition:
Element must ascending order.
No duplicate elements in ArrayList<Integer>
insert method run in O(n) times.
Here is my insert method for check duplicate element before add new element.
public void insert(int x){
//effect: Check duplicate elements if not x to the elements;
boolean found = false;
if(super.size()!=0){
for(int i=0; i<super.size(); i++){
if(super.get(i)==x){
found = true;
}
}
}
if(found){ return; }
else{ super.add(x); }
}
how can i do it? Thank you.
addition
here is my class names InSetExtra
public class IntSetExtra extends ArrayList<Integer> {
private static final long serialVersionUID = 1L;
public IntSetExtra(){
super();
}
public void insert(int x){
//effect: Check duplicate elements if not x to the elements;
boolean found = false;
if(super.size()!=0){
for(int i=0; i<super.size(); i++){
if(super.get(i)==x){
found = true;
}
}
}
if(found){ return; }
else{ super.add(x); }
}
public String toString(){
//effect: return string of this.
if(super.size()==0) return "[]";
String s = "[" + super.get(0).toString();
for(int i=1; i<super.size(); i++){
s += ", " + super.get(i).toString();
}
return s += "]";
}
}
and i need to insert a large size of elements, for example:
IntSetExtra a, b;
a = new IntSetExtra();
b = new IntSetExtra();
for(int i=0; i<30000; i++){ a.insert(2*i); }
for(int i=0; i<30000; i++){ a.insert(i); }
System.out.println("a sub = "+a.toString().substring(0, 37));
what should i do?
ps. my instructor need to use only ArrayList
We can sort an ArrayList in two ways ascending and descending order. The Collections class provides two methods to sort an ArrayList in Java.
ArrayList maintains the insertion order i.e order of the object in which they are inserted. HashSet is an unordered collection and doesn't maintain any order. ArrayList allows duplicate values in its collection.
Here is an insert method in O(n).
public void insert(int x) {
int pos = Collections.binarySearch(this, x);
if (pos < 0) {
add(-pos-1, x);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With