Collections

This is my simulation if Array class.

package main;

public class MyArrayList {

private Object[] elementData = new Object[10];
int size = 0;

public void add(Object element) {
ensureCapacity();
elementData[size++] = element;
}

public void ensureCapacity() {
if (size == elementData.length) {
Object[] arr2 = new Object[elementData.length / 2 + elementData.length];
for (int i = 0; i < elementData.length; i++) {
arr2[i] = elementData[i];
}
elementData = arr2;
}
}

public Object get(int i) {
return elementData[i];
}

public int size() {
return size;
}
}
ArrayList works kind of similar to this class.
Simulation of LinkedList:
package main;

public class User {

private User user;

public void setUser(User user) {
this.user = user;
}

public User getUser() {
return this.user;
}
}
1. ArrayList is better in select than LinkedList.
2.LinkdList is better in delete than ArrayList.
3.Vector is synchronized and thread safe.

Comparable interface:
package main;

public class User implements Comparable<User> {

public int age;

@Override
public int compareTo(User o) {
int result = 0;
if (o.age > this.age) {
return -1;
}
if (o.age < this.age) {
return 1;
}
return result;
}
}
Comparator interface:
package main;

import java.util.Comparator;

public class Main {

public static void main(String[] args) throws Exception {

Comparator<Integer> compar = new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
int i1 = (int) o1;
int i2 = (int) o2;
int result = 0;
if (i1 < i2) {
return -1;
}
if (i1 > i2) {
return 1;
}
return result;
}
};

System.out.println(compar.compare(5, 5));
}
}
package main;

import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Main {

public static void main(String[] args) throws Exception {

Comparator<User> compar = new Comparator() {
@Override
public int compare(Object o1, Object o2) {
User u1 = (User) o1;
User u2 = (User) o2;
int result = 0;
if (u1.age < u2.age) {
return -1;
}
if (u1.age > u2.age) {
return 1;
}
return result;
}
};

List<User> list = Arrays.asList(new User(3), new User(10), new User(5), new User(7), new User(1));
Collections.sort(list, compar);

for(User u : list) {
System.out.println(u.age);
}
}
}

Комментарии

Популярные сообщения из этого блога

Lesson1: JDK, JVM, JRE

SE_21_Lesson_11: Inheritance, Polymorphism

SE_21_Lesson_9: Initialization Blocks, Wrapper types, String class