Skip to content

Commit 5d48bfe

Browse files
committed
实现indexOf与get方法,并添加测试方法
1 parent f803b81 commit 5d48bfe

2 files changed

Lines changed: 45 additions & 0 deletions

File tree

src/main/java/cn/byhieg/collectiontutorial/listtutorial/SimpleLinkedList.java

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,36 @@ private void checkRangeForAdd(int index) {
7777
}
7878
}
7979

80+
public E get(int index) {
81+
checkRange(index);
82+
return node(index).item;
83+
}
84+
85+
private void checkRange(int index) {
86+
if (index >= size || index < 0) {
87+
throw new IndexOutOfBoundsException("指定index超过界限");
88+
}
89+
}
90+
91+
public int indexOf(Object element) {
92+
Node<E> cursor = first;
93+
int count = 0;
94+
while (cursor != null) {
95+
if (element != null) {
96+
if (element.equals(cursor.item)) {
97+
return count;
98+
}
99+
}else{
100+
if (cursor.item == null) {
101+
return count;
102+
}
103+
}
104+
count ++;
105+
cursor = cursor.next;
106+
}
107+
return -1;
108+
}
109+
80110
private static class Node<E> {
81111
E item;
82112
Node<E> next;

src/test/java/cn/byhieg/collectiontutorialtest/SimpleLinkedListTest.java

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,11 @@
11
package cn.byhieg.collectiontutorialtest;
22

33
import cn.byhieg.collectiontutorial.listtutorial.SimpleArrayList;
4+
import cn.byhieg.collectiontutorial.listtutorial.SimpleLinkedList;
45
import junit.framework.TestCase;
56

7+
import java.net.SocketImpl;
8+
69
/**
710
* Created by byhieg on 17/2/15.
811
* Mail to byhieg@gmail.com
@@ -16,4 +19,16 @@ public void testAdd1() throws Exception {
1619
new SimpleArrayList().add(0,10);
1720
}
1821

22+
public void testGet() throws Exception {
23+
SimpleLinkedList<String> lists = new SimpleLinkedList<>();
24+
lists.add("byhieg");
25+
System.out.println(lists.get(0));
26+
}
27+
28+
public void testIndexOf() throws Exception {
29+
SimpleLinkedList<Integer> lists = new SimpleLinkedList<>();
30+
lists.add(1);
31+
System.out.println(lists.indexOf(1));
32+
}
33+
1934
}

0 commit comments

Comments
 (0)