-
Notifications
You must be signed in to change notification settings - Fork 0
/
SimpleDataStructure.java
120 lines (101 loc) · 2.68 KB
/
SimpleDataStructure.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package Proj2;
import java.util.*;
public class SimpleDataStructure {
private String[] friends;
private int counter;
private int size = 5;
public SimpleDataStructure() {
friends = new String[size];
counter = 0;
}
/*
* Appends the other friend name to the end of this list.
*/
public boolean add(String other) {
friends[counter] = other;
counter++;
if (counter == friends.length) {
String[] temp = new String[size];
System.arraycopy(friends, 0, temp, 0, size);
this.friends = new String[size * 2];
System.arraycopy(temp, 0, friends, 0, size);
this.size = size * 2;
}
return true;
}
/** returns the name at the specified index */
public String get(int index) {
try {
return friends[index];
} catch (Exception e) {
System.out.println("IndexOutOfBounds");
}
return null;
}
/**
* removes the first occurrence of the specified element in this list if the
* list contains the name
*/
public boolean remove(String name) {
for (int i = 0; i < counter; i++) {
if (friends[i].equals(name)) {
friends[i] = null;
for (int j = i; j < friends.length - 1; j++) {
friends[j] = friends[j + 1];
}
return true;
}
}
return false;
}
/** prints all names in the array friends */
public void printFriends() {
for (int i = 0; i < friends.length; i++) {
if (friends[i] != null) {
System.out.print(friends[i] + " ");
}
}
System.out.println();
}
public void addSort(String namn) {
int index = friends.length - 1;
for (int i = 0; i < friends.length - 1; i++) {
if (friends[i + 1] != null && friends[i] != null) {
if (namn.compareTo(friends[i]) >= 0) {
if (namn.compareTo(friends[i + 1]) <= 0) {
index = i + 1;
break;
}
} else {
index = 0;
break;
}
} else if (friends[i] == null) {
index = i;
break;
}
}
for (int i = friends.length - 1; i > index; i--) {
friends[i] = friends[i - 1];
}
friends[index] = namn;
counter++;
}
public static void main(String[] arg) {
SimpleDataStructure myfriends = new SimpleDataStructure();
String[] names = { "Kalle", "Oscar", "Janne", "Joel", "Lina", "Jan", "Douglas", "Axel", "Christopher", "Lovisa",
"Patricia", "Petra", "Gustav", "Mattias" };
Arrays.sort(names);
for (int i = 0; i < names.length; i++) {
myfriends.add(names[i]);
}
myfriends.printFriends();
myfriends.remove("Douglas");
myfriends.addSort("Nikolina");
myfriends.addSort("Queen");
myfriends.addSort("Ander");
myfriends.addSort("Janna");
myfriends.printFriends();
System.out.println(myfriends.get(5));
}
}