Java-011-05ResizingArrayQueue实现

ResizingArrayQueue

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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
/******************************************************************************
* Compilation: javac ResizingArrayQueue.java
* Execution: java ResizingArrayQueue < input.txt
* Dependencies: StdIn.java StdOut.java
* Data files: https://algs4.cs.princeton.edu/13stacks/tobe.txt
*
* Queue implementation with a resizing array.
*
* % java ResizingArrayQueue < tobe.txt
* to be or not to be (2 left on queue)
*
******************************************************************************/

package edu.princeton.cs.algs4;

import java.util.Iterator;
import java.util.NoSuchElementException;

/**
* The {@code ResizingArrayQueue} class represents a first-in-first-out (FIFO)
* queue of generic items.
* It supports the usual <em>enqueue</em> and <em>dequeue</em>
* operations, along with methods for peeking at the first item,
* testing if the queue is empty, and iterating through
* the items in FIFO order.
* <p>
* This implementation uses a resizing array, which double the underlying array
* when it is full and halves the underlying array when it is one-quarter full.
* The <em>enqueue</em> and <em>dequeue</em> operations take constant amortized time.
* The <em>size</em>, <em>peek</em>, and <em>is-empty</em> operations takes
* constant time in the worst case.
* <p>
* For additional documentation, see <a href="https://algs4.cs.princeton.edu/13stacks">Section 1.3</a> of
* <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public class ResizingArrayQueue<Item> implements Iterable<Item> {
private Item[] q; // queue elements
private int n; // number of elements on queue
private int first; // index of first element of queue
private int last; // index of next available slot


/**
* Initializes an empty queue.
*/
public ResizingArrayQueue() {
q = (Item[]) new Object[2];
n = 0;
first = 0;
last = 0;
}

/**
* Is this queue empty?
* @return true if this queue is empty; false otherwise
*/
public boolean isEmpty() {
return n == 0;
}

/**
* Returns the number of items in this queue.
* @return the number of items in this queue
*/
public int size() {
return n;
}

// resize the underlying array
private void resize(int capacity) {
assert capacity >= n;
Item[] temp = (Item[]) new Object[capacity];
for (int i = 0; i < n; i++) {
temp[i] = q[(first + i) % q.length];
}
q = temp;
first = 0;
last = n;
}

/**
* Adds the item to this queue.
* @param item the item to add
*/
public void enqueue(Item item) {
// double size of array if necessary and recopy to front of array
if (n == q.length) resize(2*q.length); // double size of array if necessary
q[last++] = item; // add item
if (last == q.length) last = 0; // wrap-around
n++;
}

/**
* Removes and returns the item on this queue that was least recently added.
* @return the item on this queue that was least recently added
* @throws java.util.NoSuchElementException if this queue is empty
*/
public Item dequeue() {
if (isEmpty()) throw new NoSuchElementException("Queue underflow");
Item item = q[first];
q[first] = null; // to avoid loitering
n--;
first++;
if (first == q.length) first = 0; // wrap-around
// shrink size of array if necessary
if (n > 0 && n == q.length/4) resize(q.length/2);
return item;
}

/**
* Returns the item least recently added to this queue.
* @return the item least recently added to this queue
* @throws java.util.NoSuchElementException if this queue is empty
*/
public Item peek() {
if (isEmpty()) throw new NoSuchElementException("Queue underflow");
return q[first];
}


/**
* Returns an iterator that iterates over the items in this queue in FIFO order.
* @return an iterator that iterates over the items in this queue in FIFO order
*/
public Iterator<Item> iterator() {
return new ArrayIterator();
}

// an iterator, doesn't implement remove() since it's optional
private class ArrayIterator implements Iterator<Item> {
private int i = 0;
public boolean hasNext() { return i < n; }
public void remove() { throw new UnsupportedOperationException(); }

public Item next() {
if (!hasNext()) throw new NoSuchElementException();
Item item = q[(i + first) % q.length];
i++;
return item;
}
}

/**
* Unit tests the {@code ResizingArrayQueue} data type.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
ResizingArrayQueue<String> queue = new ResizingArrayQueue<String>();
while (!StdIn.isEmpty()) {
String item = StdIn.readString();
if (!item.equals("-")) queue.enqueue(item);
else if (!queue.isEmpty()) StdOut.print(queue.dequeue() + " ");
}
StdOut.println("(" + queue.size() + " left on queue)");
}

}

/******************************************************************************
* Copyright 2002-2018, Robert Sedgewick and Kevin Wayne.
*
* This file is part of algs4.jar, which accompanies the textbook
*
* Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
* Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
* http://algs4.cs.princeton.edu
*
*
* algs4.jar is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* algs4.jar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with algs4.jar. If not, see http://www.gnu.org/licenses.
******************************************************************************/

Java-011-04LinkedQueue实现

LinkedQueue

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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
/******************************************************************************
* Compilation: javac LinkedQueue.java
* Execution: java LinkedQueue < input.txt
* Dependencies: StdIn.java StdOut.java
* Data files: https://algs4.cs.princeton.edu/13stacks/tobe.txt
*
* A generic queue, implemented using a singly linked list.
*
* % java Queue < tobe.txt
* to be or not to be (2 left on queue)
*
******************************************************************************/

package edu.princeton.cs.algs4;

import java.util.Iterator;
import java.util.NoSuchElementException;

/**
* The {@code LinkedQueue} class represents a first-in-first-out (FIFO)
* queue of generic items.
* It supports the usual <em>enqueue</em> and <em>dequeue</em>
* operations, along with methods for peeking at the first item,
* testing if the queue is empty, and iterating through
* the items in FIFO order.
* <p>
* This implementation uses a singly linked list with a non-static nested class
* for linked-list nodes. See {@link Queue} for a version that uses a static nested class.
* The <em>enqueue</em>, <em>dequeue</em>, <em>peek</em>, <em>size</em>, and <em>is-empty</em>
* operations all take constant time in the worst case.
* <p>
* For additional documentation, see <a href="https://algs4.cs.princeton.edu/13stacks">Section 1.3</a> of
* <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public class LinkedQueue<Item> implements Iterable<Item> {
private int n; // number of elements on queue
private Node first; // beginning of queue
private Node last; // end of queue

// helper linked list class
private class Node {
private Item item;
private Node next;
}

/**
* Initializes an empty queue.
*/
public LinkedQueue() {
first = null;
last = null;
n = 0;
assert check();
}

/**
* Is this queue empty?
* @return true if this queue is empty; false otherwise
*/
public boolean isEmpty() {
return first == null;
}

/**
* Returns the number of items in this queue.
* @return the number of items in this queue
*/
public int size() {
return n;
}

/**
* Returns the item least recently added to this queue.
* @return the item least recently added to this queue
* @throws java.util.NoSuchElementException if this queue is empty
*/
public Item peek() {
if (isEmpty()) throw new NoSuchElementException("Queue underflow");
return first.item;
}

/**
* Adds the item to this queue.
* @param item the item to add
*/
public void enqueue(Item item) {
Node oldlast = last;
last = new Node();
last.item = item;
last.next = null;
if (isEmpty()) first = last;
else oldlast.next = last;
n++;
assert check();
}

/**
* Removes and returns the item on this queue that was least recently added.
* @return the item on this queue that was least recently added
* @throws java.util.NoSuchElementException if this queue is empty
*/
public Item dequeue() {
if (isEmpty()) throw new NoSuchElementException("Queue underflow");
Item item = first.item;
first = first.next;
n--;
if (isEmpty()) last = null; // to avoid loitering
assert check();
return item;
}

/**
* Returns a string representation of this queue.
* @return the sequence of items in FIFO order, separated by spaces
*/
public String toString() {
StringBuilder s = new StringBuilder();
for (Item item : this)
s.append(item + " ");
return s.toString();
}

// check internal invariants
private boolean check() {
if (n < 0) {
return false;
}
else if (n == 0) {
if (first != null) return false;
if (last != null) return false;
}
else if (n == 1) {
if (first == null || last == null) return false;
if (first != last) return false;
if (first.next != null) return false;
}
else {
if (first == null || last == null) return false;
if (first == last) return false;
if (first.next == null) return false;
if (last.next != null) return false;

// check internal consistency of instance variable n
int numberOfNodes = 0;
for (Node x = first; x != null && numberOfNodes <= n; x = x.next) {
numberOfNodes++;
}
if (numberOfNodes != n) return false;

// check internal consistency of instance variable last
Node lastNode = first;
while (lastNode.next != null) {
lastNode = lastNode.next;
}
if (last != lastNode) return false;
}

return true;
}


/**
* Returns an iterator that iterates over the items in this queue in FIFO order.
* @return an iterator that iterates over the items in this queue in FIFO order
*/
public Iterator<Item> iterator() {
return new ListIterator();
}

// an iterator, doesn't implement remove() since it's optional
private class ListIterator implements Iterator<Item> {
private Node current = first;

public boolean hasNext() { return current != null; }
public void remove() { throw new UnsupportedOperationException(); }

public Item next() {
if (!hasNext()) throw new NoSuchElementException();
Item item = current.item;
current = current.next;
return item;
}
}


/**
* Unit tests the {@code LinkedQueue} data type.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
LinkedQueue<String> queue = new LinkedQueue<String>();
while (!StdIn.isEmpty()) {
String item = StdIn.readString();
if (!item.equals("-"))
queue.enqueue(item);
else if (!queue.isEmpty())
StdOut.print(queue.dequeue() + " ");
}
StdOut.println("(" + queue.size() + " left on queue)");
}
}

/******************************************************************************
* Copyright 2002-2018, Robert Sedgewick and Kevin Wayne.
*
* This file is part of algs4.jar, which accompanies the textbook
*
* Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
* Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
* http://algs4.cs.princeton.edu
*
*
* algs4.jar is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* algs4.jar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with algs4.jar. If not, see http://www.gnu.org/licenses.
******************************************************************************/

Java-011-03Queue实现

Queue

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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
/******************************************************************************
* Compilation: javac Queue.java
* Execution: java Queue < input.txt
* Dependencies: StdIn.java StdOut.java
* Data files: https://algs4.cs.princeton.edu/13stacks/tobe.txt
*
* A generic queue, implemented using a linked list.
*
* % java Queue < tobe.txt
* to be or not to be (2 left on queue)
*
******************************************************************************/

package edu.princeton.cs.algs4;

import java.util.Iterator;
import java.util.NoSuchElementException;

/**
* The {@code Queue} class represents a first-in-first-out (FIFO)
* queue of generic items.
* It supports the usual <em>enqueue</em> and <em>dequeue</em>
* operations, along with methods for peeking at the first item,
* testing if the queue is empty, and iterating through
* the items in FIFO order.
* <p>
* This implementation uses a singly linked list with a static nested class for
* linked-list nodes. See {@link LinkedQueue} for the version from the
* textbook that uses a non-static nested class.
* See {@link ResizingArrayQueue} for a version that uses a resizing array.
* The <em>enqueue</em>, <em>dequeue</em>, <em>peek</em>, <em>size</em>, and <em>is-empty</em>
* operations all take constant time in the worst case.
* <p>
* For additional documentation, see <a href="https://algs4.cs.princeton.edu/13stacks">Section 1.3</a> of
* <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*
* @param <Item> the generic type of an item in this queue
*/
public class Queue<Item> implements Iterable<Item> {
private Node<Item> first; // beginning of queue
private Node<Item> last; // end of queue
private int n; // number of elements on queue

// helper linked list class
private static class Node<Item> {
private Item item;
private Node<Item> next;
}

/**
* Initializes an empty queue.
*/
public Queue() {
first = null;
last = null;
n = 0;
}

/**
* Returns true if this queue is empty.
*
* @return {@code true} if this queue is empty; {@code false} otherwise
*/
public boolean isEmpty() {
return first == null;
}

/**
* Returns the number of items in this queue.
*
* @return the number of items in this queue
*/
public int size() {
return n;
}

/**
* Returns the item least recently added to this queue.
*
* @return the item least recently added to this queue
* @throws NoSuchElementException if this queue is empty
*/
public Item peek() {
if (isEmpty()) throw new NoSuchElementException("Queue underflow");
return first.item;
}

/**
* Adds the item to this queue.
*
* @param item the item to add
*/
public void enqueue(Item item) {
Node<Item> oldlast = last;
last = new Node<Item>();
last.item = item;
last.next = null;
if (isEmpty()) first = last;
else oldlast.next = last;
n++;
}

/**
* Removes and returns the item on this queue that was least recently added.
*
* @return the item on this queue that was least recently added
* @throws NoSuchElementException if this queue is empty
*/
public Item dequeue() {
if (isEmpty()) throw new NoSuchElementException("Queue underflow");
Item item = first.item;
first = first.next;
n--;
if (isEmpty()) last = null; // to avoid loitering
return item;
}

/**
* Returns a string representation of this queue.
*
* @return the sequence of items in FIFO order, separated by spaces
*/
public String toString() {
StringBuilder s = new StringBuilder();
for (Item item : this) {
s.append(item);
s.append(' ');
}
return s.toString();
}

/**
* Returns an iterator that iterates over the items in this queue in FIFO order.
*
* @return an iterator that iterates over the items in this queue in FIFO order
*/
public Iterator<Item> iterator() {
return new ListIterator<Item>(first);
}

// an iterator, doesn't implement remove() since it's optional
private class ListIterator<Item> implements Iterator<Item> {
private Node<Item> current;

public ListIterator(Node<Item> first) {
current = first;
}

public boolean hasNext() { return current != null; }
public void remove() { throw new UnsupportedOperationException(); }

public Item next() {
if (!hasNext()) throw new NoSuchElementException();
Item item = current.item;
current = current.next;
return item;
}
}


/**
* Unit tests the {@code Queue} data type.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
Queue<String> queue = new Queue<String>();
while (!StdIn.isEmpty()) {
String item = StdIn.readString();
if (!item.equals("-"))
queue.enqueue(item);
else if (!queue.isEmpty())
StdOut.print(queue.dequeue() + " ");
}
StdOut.println("(" + queue.size() + " left on queue)");
}
}

/******************************************************************************
* Copyright 2002-2018, Robert Sedgewick and Kevin Wayne.
*
* This file is part of algs4.jar, which accompanies the textbook
*
* Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
* Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
* http://algs4.cs.princeton.edu
*
*
* algs4.jar is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* algs4.jar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with algs4.jar. If not, see http://www.gnu.org/licenses.
******************************************************************************/

Java-011-02LinkedStack实现

LinkedStack

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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
/******************************************************************************
* Compilation: javac LinkedStack.java
* Execution: java LinkedStack < input.txt
* Dependencies: StdIn.java StdOut.java
* Data files: https://algs4.cs.princeton.edu/13stacks/tobe.txt
*
* A generic stack, implemented using a linked list. Each stack
* element is of type Item.
*
* % more tobe.txt
* to be or not to - be - - that - - - is
*
* % java LinkedStack < tobe.txt
* to be not that or be (2 left on stack)
*
******************************************************************************/

package edu.princeton.cs.algs4;

import java.util.Iterator;
import java.util.NoSuchElementException;


/**
* The {@code LinkedStack} class represents a last-in-first-out (LIFO) stack of
* generic items.
* It supports the usual <em>push</em> and <em>pop</em> operations, along with methods
* for peeking at the top item, testing if the stack is empty, and iterating through
* the items in LIFO order.
* <p>
* This implementation uses a singly linked list with a non-static nested class for
* linked-list nodes. See {@link Stack} for a version that uses a static nested class.
* The <em>push</em>, <em>pop</em>, <em>peek</em>, <em>size</em>, and <em>is-empty</em>
* operations all take constant time in the worst case.
* <p>
* For additional documentation,
* see <a href="https://algs4.cs.princeton.edu/13stacks">Section 1.3</a> of
* <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public class LinkedStack<Item> implements Iterable<Item> {
private int n; // size of the stack
private Node first; // top of stack

// helper linked list class
private class Node {
private Item item;
private Node next;
}

/**
* Initializes an empty stack.
*/
public LinkedStack() {
first = null;
n = 0;
assert check();
}

/**
* Is this stack empty?
* @return true if this stack is empty; false otherwise
*/
public boolean isEmpty() {
return first == null;
}

/**
* Returns the number of items in the stack.
* @return the number of items in the stack
*/
public int size() {
return n;
}

/**
* Adds the item to this stack.
* @param item the item to add
*/
public void push(Item item) {
Node oldfirst = first;
first = new Node();
first.item = item;
first.next = oldfirst;
n++;
assert check();
}

/**
* Removes and returns the item most recently added to this stack.
* @return the item most recently added
* @throws java.util.NoSuchElementException if this stack is empty
*/
public Item pop() {
if (isEmpty()) throw new NoSuchElementException("Stack underflow");
Item item = first.item; // save item to return
first = first.next; // delete first node
n--;
assert check();
return item; // return the saved item
}


/**
* Returns (but does not remove) the item most recently added to this stack.
* @return the item most recently added to this stack
* @throws java.util.NoSuchElementException if this stack is empty
*/
public Item peek() {
if (isEmpty()) throw new NoSuchElementException("Stack underflow");
return first.item;
}

/**
* Returns a string representation of this stack.
* @return the sequence of items in the stack in LIFO order, separated by spaces
*/
public String toString() {
StringBuilder s = new StringBuilder();
for (Item item : this)
s.append(item + " ");
return s.toString();
}

/**
* Returns an iterator to this stack that iterates through the items in LIFO order.
* @return an iterator to this stack that iterates through the items in LIFO order.
*/
public Iterator<Item> iterator() {
return new ListIterator();
}

// an iterator, doesn't implement remove() since it's optional
private class ListIterator implements Iterator<Item> {
private Node current = first;
public boolean hasNext() { return current != null; }
public void remove() { throw new UnsupportedOperationException(); }

public Item next() {
if (!hasNext()) throw new NoSuchElementException();
Item item = current.item;
current = current.next;
return item;
}
}


// check internal invariants
private boolean check() {

// check a few properties of instance variable 'first'
if (n < 0) {
return false;
}
if (n == 0) {
if (first != null) return false;
}
else if (n == 1) {
if (first == null) return false;
if (first.next != null) return false;
}
else {
if (first == null) return false;
if (first.next == null) return false;
}

// check internal consistency of instance variable n
int numberOfNodes = 0;
for (Node x = first; x != null && numberOfNodes <= n; x = x.next) {
numberOfNodes++;
}
if (numberOfNodes != n) return false;

return true;
}

/**
* Unit tests the {@code LinkedStack} data type.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
LinkedStack<String> stack = new LinkedStack<String>();
while (!StdIn.isEmpty()) {
String item = StdIn.readString();
if (!item.equals("-"))
stack.push(item);
else if (!stack.isEmpty())
StdOut.print(stack.pop() + " ");
}
StdOut.println("(" + stack.size() + " left on stack)");
}
}


/******************************************************************************
* Copyright 2002-2018, Robert Sedgewick and Kevin Wayne.
*
* This file is part of algs4.jar, which accompanies the textbook
*
* Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
* Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
* http://algs4.cs.princeton.edu
*
*
* algs4.jar is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* algs4.jar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with algs4.jar. If not, see http://www.gnu.org/licenses.
******************************************************************************/

Java-011-01Stack实现

Stack实现

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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
/******************************************************************************
* Compilation: javac Stack.java
* Execution: java Stack < input.txt
* Dependencies: StdIn.java StdOut.java
* Data files: https://algs4.cs.princeton.edu/13stacks/tobe.txt
*
* A generic stack, implemented using a singly linked list.
* Each stack element is of type Item.
*
* This version uses a static nested class Node (to save 8 bytes per
* Node), whereas the version in the textbook uses a non-static nested
* class (for simplicity).
*
* % more tobe.txt
* to be or not to - be - - that - - - is
*
* % java Stack < tobe.txt
* to be not that or be (2 left on stack)
*
******************************************************************************/

package edu.princeton.cs.algs4;

import java.util.Iterator;
import java.util.NoSuchElementException;


/**
* The {@code Stack} class represents a last-in-first-out (LIFO) stack of generic items.
* It supports the usual <em>push</em> and <em>pop</em> operations, along with methods
* for peeking at the top item, testing if the stack is empty, and iterating through
* the items in LIFO order.
* <p>
* This implementation uses a singly linked list with a static nested class for
* linked-list nodes. See {@link LinkedStack} for the version from the
* textbook that uses a non-static nested class.
* See {@link ResizingArrayStack} for a version that uses a resizing array.
* The <em>push</em>, <em>pop</em>, <em>peek</em>, <em>size</em>, and <em>is-empty</em>
* operations all take constant time in the worst case.
* <p>
* For additional documentation,
* see <a href="https://algs4.cs.princeton.edu/13stacks">Section 1.3</a> of
* <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*
* @param <Item> the generic type of an item in this stack
*/
public class Stack<Item> implements Iterable<Item> {
private Node<Item> first; // top of stack
private int n; // size of the stack

// helper linked list class
private static class Node<Item> {
private Item item;
private Node<Item> next;
}

/**
* Initializes an empty stack.
*/
public Stack() {
first = null;
n = 0;
}

/**
* Returns true if this stack is empty.
*
* @return true if this stack is empty; false otherwise
*/
public boolean isEmpty() {
return first == null;
}

/**
* Returns the number of items in this stack.
*
* @return the number of items in this stack
*/
public int size() {
return n;
}

/**
* Adds the item to this stack.
*
* @param item the item to add
*/
public void push(Item item) {
Node<Item> oldfirst = first;
first = new Node<Item>();
first.item = item;
first.next = oldfirst;
n++;
}

/**
* Removes and returns the item most recently added to this stack.
*
* @return the item most recently added
* @throws NoSuchElementException if this stack is empty
*/
public Item pop() {
if (isEmpty()) throw new NoSuchElementException("Stack underflow");
Item item = first.item; // save item to return
first = first.next; // delete first node
n--;
return item; // return the saved item
}


/**
* Returns (but does not remove) the item most recently added to this stack.
*
* @return the item most recently added to this stack
* @throws NoSuchElementException if this stack is empty
*/
public Item peek() {
if (isEmpty()) throw new NoSuchElementException("Stack underflow");
return first.item;
}

/**
* Returns a string representation of this stack.
*
* @return the sequence of items in this stack in LIFO order, separated by spaces
*/
public String toString() {
StringBuilder s = new StringBuilder();
for (Item item : this) {
s.append(item);
s.append(' ');
}
return s.toString();
}


/**
* Returns an iterator to this stack that iterates through the items in LIFO order.
*
* @return an iterator to this stack that iterates through the items in LIFO order
*/
public Iterator<Item> iterator() {
return new ListIterator<Item>(first);
}

// an iterator, doesn't implement remove() since it's optional
private class ListIterator<Item> implements Iterator<Item> {
private Node<Item> current;

public ListIterator(Node<Item> first) {
current = first;
}

public boolean hasNext() {
return current != null;
}

public void remove() {
throw new UnsupportedOperationException();
}

public Item next() {
if (!hasNext()) throw new NoSuchElementException();
Item item = current.item;
current = current.next;
return item;
}
}


/**
* Unit tests the {@code Stack} data type.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
Stack<String> stack = new Stack<String>();
while (!StdIn.isEmpty()) {
String item = StdIn.readString();
if (!item.equals("-"))
stack.push(item);
else if (!stack.isEmpty())
StdOut.print(stack.pop() + " ");
}
StdOut.println("(" + stack.size() + " left on stack)");
}
}


/******************************************************************************
* Copyright 2002-2018, Robert Sedgewick and Kevin Wayne.
*
* This file is part of algs4.jar, which accompanies the textbook
*
* Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
* Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
* http://algs4.cs.princeton.edu
*
*
* algs4.jar is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* algs4.jar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with algs4.jar. If not, see http://www.gnu.org/licenses.
******************************************************************************/

Java_011_数据结构初探

参考资料

哈希表 (Hash Table)

  • 哈希表是一种将键映射到值的数据结构。它用哈希方程来将键映射到小范围的指数(一般为[0..哈希表大小-1])
  • 可视化解析哈希表

栈 (Stack)

  • 栈是计算机科学中一种特殊的串列形式的抽象数据类型,其特殊之处在于只能允许在链表或数组的一端(称为栈顶端指针,英语:top)进行加入数据(英语:push)和输出数据(英语:pop)的运算。
  • 由于栈数据结构只允许在一端进行操作,因而按照后进先出(LIFO, Last In First Out)的原理运作.

数组实现栈
链表实现栈

队列 (Queue)

  • 是先进先出(FIFO, First-In-First-Out)的线性表。在具体应用中通常用链表或者数组来实现。队列只允许在后端(称为rear)进行插入操作,在前端(称为front)进行删除操作。

数组实现队列
链表实现队列

参考资料

时间空间复杂度

表示法

  • 表示法O(n^n), O(n!), O(n²), O(n), O(1), O(nlogn)
  • 这些是规模的量级! 和N (数据量的大小)成比例的

目的

  • 评估算法的效率, 也就是需要耗费的时间(计算量)和空间(存储占用).
  • 主要关注点是相对于输入数据的规模
    • 快速排序 1000000
    • 冒泡排序 100
  • 简单来说, 时间复杂度就是基本语句的运算次数.

学习目标

时间复杂度的计算和证明是可以比较困难的. 但是常见的数据结构和算法的时间复杂度是很容易大致计算的!

主要目标是理解不同时间复杂度相对于输入数据量的增长速度是不一样的!

常用复杂度对比

  1. 数多少个循环嵌套: 平方, 立方, 还是4次方
  2. 如果遇到有”二分”这样的结构, 一般会是包含logn
  3. 数搜索空间

如何锻炼算法能力

  • 多做题!多训练!

哈希表

  1. 提供一个存储结构, 其中存储的是Key-Value对, Key和Value可以是任意的类型

    • 类似于数组(伪数组): 可以使用数组的下标索引(数字!!!!)去访问存储的数据!
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      Key可以是任何类型的! arr[名字] = 人的身份对象

      // 用js了
      var arr = [1,2,3];
      arr[0] // 1
      arr[1] // 2
      arr[2] // 3
      arr.length // 3

      var obj ={
      "0":1,
      "1":2,
      "2":3,
      "length":3
      }
      obj["0"] //1
      obj["1"] //2
      obj["2"] //3
      obj["length"] //3
  • 类似于f(x) = y这样的函数, 我们可以设置任意的f(x1) = y1, 或者f(x2) = y2.
  • 或者访问: a = f(x1)

它支持四种操作: 增删改查!

增加, 查询,修改和删除操作的时间复杂度都近似于 O(1) , 也不依赖于插入的顺序. 也就是随机访问(想访问哪个数据就马上访问哪个数据!)

不可以对 哈希表进行排序

  • 存储在哈希表里的数据没有顺序!!! 不可以对哈希表进行排序

数组和哈希表不一样的点

  • 数组的key只支持数字的, 但是哈希表支持更多的数据类型!
  • 数组在中间插入数据操作, 时间复杂度一般不是O(1)

一个数据结构, 用于存储数据. 支持两种操作:

  • 插入数据 (push);
  • 取出数据 (pop); 获得数据, 同时把数据从栈中删除
  • 所有操作的时间复杂度度为O(1)

最重要的是, 哈希表可以随机访问. 但是栈对数据的访问顺序有规定. 遵循一个规则: 先进后出, 后进先出. 也就是只能访问当最近放进到栈里面的那个数据!

队列

一个类似于栈的数据结构, 用于存储数据, 同样支持两种操作:

  • 插入数据 (push);
  • 取出数据 (pop); 获得数据, 同时从队列中删除
  • 所有操作的时间复杂度为O(1)

队列遵循一个规则: 先进先出, 后进后出. 也就是从队列中取出数据的顺序和放进去的顺序是一样的!

遇到这种描述方式的时候, 尝试使用接口! 抽象数据类型

数据结构学习方法

  • 理解数据结构的操作!时间复杂度
  • 理解数据结构的属性
  • 理解数据结构的内部构造!!!
    • 这部分不用马上搞清楚,先把它用起来
    • 当你感兴趣,当你有时间,当你抑制不住你的好奇和求知欲就会自然而然去探索它的内部构造!!!
  • 应用—-> 训练!大量的训练!大量大量的训练! 力扣300题是起点(一年时间做完)
    • 在美国 没有力扣300题 基本投简历就挂了
    • 但是如果你这些过了,你可以不会安卓,不会java 不会web不会mysql都无所谓
    • 抓住核心本质, 教你redis 一步步部署有用吗!
    • 想要职业生涯更广阔这是一个非常值得投入的地方

一定要给自己鼓励!不会就拿时间去磨,很多东西你想去做,就不会考虑困难

  • 追一个女孩子,被拒就不追了吗?
  • 这个问题解决了对我们利益足部足够大?
  • 目标不是学会,而是学了这个扩展视野获得经济

question

1简述哈希表的操作及其相应满足的特性

  • 增删查快
  • 修改慢
  • 时间负责度O(1)
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
import java.util.*;

public class T001_Hash {
public static void main(String[] args) {

Map<String,String> hashMap = new HashMap<>();

// 增删改查

// 增
hashMap.put("张三","29");
hashMap.put("李四","22");
hashMap.put("王五","18");

// 改
// 如果key相同, 后面的覆盖前面的
hashMap.put("王五","99");

// 查
// 根据key获取值
System.out.println(hashMap.get("王五")); // 99

// 判断key是否存在
System.out.println(hashMap.containsKey("王五"));
System.out.println(hashMap.containsKey("赵六"));

// 删除
/*
* 删除成功则 返回删除的值,删除失败返回 null
* */
System.out.println(hashMap.remove("王五")); // 99
System.out.println(hashMap.remove("赵六")); // null

// 获取所有key
Set<String> key_set = hashMap.keySet();

// 循环 map
for (String key:key_set) {
String value = hashMap.get(key);
System.out.println("key:" + key + ",value:" + value);
}

// 获取所有value hashMap.values() 返回的是Collection 向下转型报错
// 没法 这样 List<String> valuesList = (List<String>) map.values();
// 在ArrayList中,有一个构造函数 可以接受一个集合类型的参数,然后返回一个list
List<String> valuesList = new ArrayList<String>(hashMap.values());
for(String str:valuesList){
System.out.println(str);
}

// k-v对 的数量
System.out.println(hashMap.size()); // 2

// 清空 所有数据
hashMap.clear();
System.out.println(hashMap.size()); // 0

}
}

2 简述栈的操作及其满足的特性或限制和时间复杂度

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
package com.oop.demo.data;

import java.util.Stack;

public class Test2 {
public static void main(String[] args) {

// 栈
Stack<Integer> stack = new Stack<Integer>();

// 压栈
stack.push(3);
stack.push(5);

// 出栈
System.out.println(stack.pop()); // 5
System.out.println(stack.pop()); // 3


stack.push(66);
// 只看顶部数据,但是不删除
System.out.println(stack.peek()); // 66

// 看栈是否为空
System.out.println(stack.empty());

// 深度优先搜索
// 汉诺塔
// 匹配 [({})] 是否配对
}
}

3 简述队列的操作及其满足的特性或限制和时间复杂度

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
package com.oop.demo.data;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

public class Test2 {
public static void main(String[] args) {
// 队列 先进先出
// Queue 是个接口 无法实例化
// Queue<Integer> queue = new Queue<Integer>();

Queue<Integer> queue = new LinkedList<Integer>();


queue.add(3);
queue.add(5);

System.out.println(queue.poll()); // 3
System.out.println(queue.poll()); // 5

Integer firstVal = queue.peek();

// queue.isEmpty() 和 上面的 Stack 不一致 stack.empty()
// 这就是因为 接口不稳定导致,以至于现在就无法改了,因为已经批量使用了
System.out.println( queue.isEmpty());

// 消息队列
// 买票
// 广度优先搜索
}
}

4 栈的练习题

5 队列练习题

6 两数之和

js版本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
var twoSum = function(nums, target) {
let res = [];

// 第一次的思路 两层循环
/*
第一层循环锁定 i=0 的值 1
第二层循环从 j = i+1 之后开始循环 比对(因为循环时不该包括已经选定的值)
只要 nums[i] + nums[j] === target 就返回结果
*/
for(let i = 0;i<nums.length-1;i++){
for(let j = i + 1;j<nums.length;j++){
if(nums[i] + nums[j] === target){
res.push(i,j);
break;
}
}
}
return res;
};

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
public class Solution {

public static int[] twoSum(int[] nums, int target) {
int[] res = new int[2];
// 第一次的思路 两层循环
/*
第一层循环锁定 i=0 的值 1
第二层循环从 j = i+1 之后开始循环 比对(因为循环时不该包括已经选定的值)
只要 nums[i] + nums[j] === target 就返回结果
*/
for(int i = 0;i<nums.length-1;i++){
for(int j = i + 1;j<nums.length;j++){
if(nums[i] + nums[j] == target){
res[0] = i;
res[1] = j;
break;
}
}
}
return res;
}

public static void main(String[] args) {
int[][] arr = {
{2,7,11,15},
{2,6,11,15},
{0,7,1,3},
{5,7,110,12},
{10,90,101,1},
};
int[] target = {
9,
13,
4,
19,
111
};

for (int i = 0; i < arr.length; i++) {
int[] res = twoSum(arr[i],target[i]);
System.out.println("["+res[0]+","+res[1]+"]");
}
}
}

7字母统计

给一个字符串 (只包含26个字母),统计每个字母出现的次数(返回类型为HashMap)

样例

  • 给出 numbers = “alexyang”, 返回一个HashMap counts,里面包含所有26个字母出现的次数
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
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;

public class WordCounter {
public static HashMap count(String input) {
HashMap<String,Integer> map = new HashMap<String,Integer>();
// 写具体实现
for (int i = 0; i <input.length() ; i++) {
String key = input.charAt(i) + "";
if(map.containsKey(key)){
int value = map.get(key);
map.put(key,value+1);
}else{
map.put(key,1);
}
}
return map;
}


public static void main(String[] args) {
String[] a = {"alexyang","huangjx","zhangsan","bbbbdddd","abbccc"};
for (int i = 0; i < a.length ; i++) {
HashMap<String,Integer> map = count(a[i]);
System.out.println(map);
}
}
}
  • 请实现count方法.
  • 然后在main()方法中至少写5组测试用例, 测试你的实现.

8 括号匹配序列

  • 给定一个字符串所表示的括号序列,包含以下字符: ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[‘ and ‘]’, 判定是否是有效的括号序列。
  • 例子
    1
    括号必须依照 "()" 顺序表示, "()[]{}" 是有效的括号,但 "([)]"则是无效的括号。
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
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

public class T003Solution {
public static void main(String[] args) {
String[] arr = {"{}{}()()[][]","{[()()()[]]}","{(([])([])())}","[]]","[[[["};
for (int i = 0; i < arr.length; i++) {
boolean res = isValidParentheses(arr[i]);
System.out.println(res);
}
}

public static boolean isValidParentheses(String s) {
Map<String,String> map = new HashMap<String,String>();
map.put("{","}");
map.put("(",")");
map.put("[","]");
map.put("}","{");
map.put(")","(");
map.put("]","[");
Stack<String> stack = new Stack<String>();
for (int i = 0; i < s.length() ; i++) {
String currentVal = s.charAt(i) + "";
if(stack.empty()){
stack.push(currentVal);
}else{
String convertVal = map.get(currentVal);
String topValue = stack.peek();
if(topValue.equals(convertVal)){
stack.pop();
}
}
}
return stack.empty();
}
}

Java_010_面向对象二

代码参考

多态

  • 父类对象指向子类实例

如下例子 Man / Dog /Car 都会跑

  • 如果单独调用自己的 manRun/dogRun/carRun 就很重复和耦合
  • 而使用多态就可以只用一个 objRun 此时只要传递实现类 调用即可

便利性

  • 少写重复代码
  • 功能易于扩展和维护
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
package com.oop.demo.aaa;

public class TestA {
public static void main(String[] args) {

// 不使用多态
Man man1 = new Man();
Dog dog1 = new Dog();
Car car1 = new Car();
System.out.println("不使用多态");
manRun(man1);
dogRun(dog1);
carRun(car1);

System.out.println("使用多态");
Runable man2 = new Man();
Runable dog2 = new Dog();
Runable car2 = new Car();

// 使用多态
objRun(man2);
objRun(dog2);
objRun(car2);


}

public static void objRun(Runable runObj){
runObj.run();
}

public static void manRun(Man man){
man.run();
}
public static void dogRun(Dog dog){
dog.run();
}
public static void carRun(Car car){
car.run();
}
}

interface Runable{
void run();
}

class Man implements Runable{

@Override
public void run() {
System.out.println("两条腿跑");
}
}

class Dog implements Runable{

@Override
public void run() {
System.out.println("四条腿跑");
}
}

class Car implements Runable{
@Override
public void run() {
System.out.println("四个轱辘跑。。。。");
}
}

抽象类(未构建完成的类,残缺的类)

举个例子:抽象类就像一个梦想,但可能要经历几代人来实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/*
伪代码,开发里肯定用英文
*/
abstract class 东汉末年没落的皇族{
void 招兵买马( );
void 统一天下( );
}
// 刘备由于没统一天下,所以他把重任交给了后代
abstract class 刘备 extends 东汉末年没落的皇族{
void 招兵买马( ){
System.out.println("刘关张桃园结义");
System.out.println("诸葛加入,三分天下");
}
}

// 虽然刘禅没统一,我们暂且假设他成功了吧!不然写不完了
class 刘禅 extends 刘备{
void 统一天下( ){
System.out.println("在梦里!!!终于统一了天下");
}
}

接口

  • 更具体的某种行为/特质
1
2
如上面的 Runable 接口
不是所有事物都会 run的 如盒子/山
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
interface 充电接口{
void 充电( );
}

class 手机 implements Runable{
@Override
public void 充电() {
System.out.println("手机充电");
}
}

class 电脑 implements Runable{
@Override
public void 充电() {
System.out.println("电脑充电");
}
}

接口和抽象类的区别

  • 它们表示的不一样

    • 接口更倾向于某种特性/行为

      1
      2
      3
      4
      充电功能
      安卓手机充电 usb头
      电脑充电 圆头
      air平板充电 type-c头
    • 抽象类是更倾向于某类事物的特性/行为

      1
      2
      3
      4
      5
      动物
      毛发
      行走
      吼叫
      吃饭

Java_009_面向对象编程一

封装

  • 在⾯面向对象程式设计⽅方法中, 封装(英语:Encapsulation)是指⼀一种将类实现细节部分包装, 隐藏起 来的方法.
  • 封装⽅式: 类.
  • 对类的内部状态的访问进行控制, 只提供该提供的信息
  • 把代码分成两个部分: 接口 和 实现!
  • 接⼝因为涉及和外部的交互, 对⽤户暴露, 应该保持稳定. 例如: API和库
  • 内部实现不需要暴露给外部用户. 在接⼝功能不被影响的前提下, 可以随意修改和重构
  • 良好的封装是解耦的基础!
  • 代码实例例

访问修饰符

  • public
  • protected
  • default
  • private
1
2
3
4
5
访问权限   类   包  子类  其他包
     public ∨ ∨ ∨ ∨ (对任何人都是可用的)
     protected ∨ ∨ ∨ ×    (继承的类可以访问以及和private一样的权限)
     default ∨ ∨ × ×    (包访问权限,即在整个包内均可被访问)
     private ∨ × × ×    (除类型创建者和类型的内部方法之外的任何人都不能访问的元素)

继承

get 和 set

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
class Student {

private String name; // 姓名
private int age; // 年龄
private boolean male; // 是不是爷们儿

public void setMale(boolean b) {
male = b;
}

public boolean isMale() {
return male;
}

public void setName(String str) {
name = str;
}

public String getName() {
return name;
}

public void setAge(int num) {
age = num;
}

public int getAge() {
return age;
}
}

构造方法的重载

注意事项:

  1. 构造方法的名称必须和所在的类名称完全一样,就连大小写也要一样
  2. 构造方法不要写返回值类型,连void都不写
  3. 构造方法不能return一个具体的返回值
  4. 如果没有编写任何构造方法,那么编译器将会默认赠送一个构造方法,没有参数、方法体什么事情都不做。
    public Student() {}
  5. 一旦编写了至少一个构造方法,那么编译器将不再赠送。
  6. 构造方法也是可以进行重载的。

重载:方法名称相同,参数列表不同。

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
/*
构造方法是专门用来创建对象的方法,当我们通过关键字new来创建对象时,其实就是在调用构造方法。
格式:
public 类名称(参数类型 参数名称) {
方法体
}
*/
public class Student {

// 成员变量
private String name;
private int age;

// 无参数的构造方法
public Student() {
System.out.println("无参构造方法执行啦!");
}

// 全参数的构造方法
public Student(String name, int age) {
System.out.println("全参构造方法执行啦!");
this.name = name;
this.age = age;
}

// Getter Setter
public void setName(String name) {
this.name = name;
}

public String getName() {
return name;
}

public void setAge(int age) {
this.age = age;
}

public int getAge() {
return age;
}

}

final

final关键字代表最终、不可改变的。
常见四种用法:

  1. 可以用来修饰一个类
  2. 可以用来修饰一个方法
  3. 还可以用来修饰一个局部变量
  4. 还可以用来修饰一个成员变量
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
int num1 = 10;
System.out.println(num1); // 10
num1 = 20;
System.out.println(num1); // 20

// 一旦使用final用来修饰局部变量,那么这个变量就不能进行更改。
// “一次赋值,终生不变”
final int num2 = 200;
System.out.println(num2); // 200

// num2 = 250; // 错误写法!不能改变!
// num2 = 200; // 错误写法!

// 正确写法!只要保证有唯一一次赋值即可
final int num3;
num3 = 30;

// 对于基本类型来说,不可变说的是变量当中的数据不可改变
// 对于引用类型来说,不可变说的是变量当中的地址值不可改变
Student stu1 = new Student("赵丽颖");
System.out.println(stu1);
System.out.println(stu1.getName()); // 赵丽颖
stu1 = new Student("霍建华");
System.out.println(stu1);
System.out.println(stu1.getName()); // 霍建华
System.out.println("===============");

final Student stu2 = new Student("高圆圆");
// 错误写法!final的引用类型变量,其中的地址不可改变
// stu2 = new Student("赵又廷");
System.out.println(stu2.getName()); // 高圆圆
stu2.setName("高圆圆圆圆圆圆");
System.out.println(stu2.getName()); // 高圆圆圆圆圆圆

JavaBean

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
/*
一个标准的类通常要拥有下面四个组成部分:
1. 所有的成员变量都要使用private关键字修饰
2. 为每一个成员变量编写一对儿Getter/Setter方法
3. 编写一个无参数的构造方法
4. 编写一个全参数的构造方法
这样标准的类也叫做Java Bean
*/
class Student {

private String name; // 姓名
private int age; // 年龄

public Student() {
}

public Student(String name, int age) {
this.name = name;
this.age = age;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}
}

Java_008_IO和异常

I/O和流

  • I/O是Input和Output的缩写
  • 从读写设备,包括硬盘⽂文件,内存,键盘输⼊入,屏幕输出,⽹网络
  • 输⼊入输出 ”内容” (字节或⽂文本)
  • 流是对输⼊入输出设备的⼀一种抽象
  • 从流中读取内容,输出内容到流中
  • “Linux中⼀一起都是⽂文件”
  • 从程序的⻆角度, 就是对读写设备进⾏行行封装, ⽐比如:创建⼀一个对象, 然后调⽤用⽅方法 读取(输出)内容, 然后对象会更更新当前⽂文件的位置

标准输⼊入输出流

标准输出流

System.in;

字节流

  • InputStream
    • System.in
    • FileInputStream
  • OutputStream
    • System.out
    • FileOutputStream
    • BufferedInputStream和BufferedOutputStream
  • Stream⽤用于直接处理理”字节”

字符流

  • Reader
  • InputStreamReader
    • FileReader
    • BufferedReader
      bufferedReader.readLine();

字符流

  • Writer
  • OutputStreamWriter
    • FileWriter BufferedWriter
      bufferedWriter.write(String);
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
// System.out 标准输出流
PrintStream out = System.out;


System.out.println("hello java");

// 标准输入
InputStream in = System.in;

InputStreamReader stdReader = new InputStreamReader(System.in);


char[] buffer = new char[20];

int length = stdReader.read(buffer);

System.out.println(length);
/*
* 我们读取字符串的时候,需要用到其他的读取
* 把字节转换成字符串
*
* */


// 从一个文件读取内容,输出到另一个文件
FileInputStream input = new FileInputStream("res/input.txt");
FileOutputStream output = new FileOutputStream("res/output.txt");

InputStreamReader reader = new InputStreamReader(input,"UTF-8");
OutputStreamWriter writer = new OutputStreamWriter(output,"UTF-8");

BufferedReader bufferedReader = new BufferedReader(reader);
PrintWriter printWriter = new PrintWriter(writer);

// String context = "";
// for(String line = bufferedReader.readLine() ;line != null;line = bufferedReader.readLine()){
// // 处理这一行
// context += line;
// }

String context2 = "";
String line = null;
while(( line = bufferedReader.readLine()) != null){
// 加 \n 是因为 拼接的时候去掉了
context2 += line + "\n";
}

reader.close();
input.close();

System.out.println(context2);
printWriter.print(context2);

printWriter.close();
output.close();

IOUtils

  • IOUtils是Apache开源项⽬目的⼀一个很⼴广泛使⽤用的IO⼯工具库
  • 主要提供更更⾼高抽象程度的IO访问⼯工具,⽅方便便写IO相关的代码
  • 常⽤用类
    • FileUtils
    • Charset
    • DirectoryWalker
    • copyUtils

异常

  • Java异常 (Exception) 是⽤用来在正常程序运⾏行行流程中遇到”异常”情况, 跳出正 常运⾏行行流程, 进⾏行行出错处理理的⼀一种机制
  • 异常类: new Exception();
  • 异常捕捉语句句:
  • try {正常代码;} catch (Exception e) {处理理异常代码;}

异常 和 NULL

  • Null是⼀一个值, 可以赋值给所有类型的变量量
  • 表达的是”空”, 指这个变量量不不指向任何对象
  • Integer x = null; Object object = null;
  • 当调⽤用 x.xxx() 或 object.test() 时候, 会返回NullpointerException;
  • 这是⾮非常常⻅见的⼀一种错误, 所以使⽤用⼀一个变量量的时候, 需要检查这个变量量是否
    指向null, 以免出错

Java_007_java基础

常量和变量

常量:在程序运行期间,固定不变的量。

常量的分类:

  1. 字符串常量:凡是用双引号引起来的部分,叫做字符串常量。例如:”abc”、”Hello”、”123”
  2. 整数常量:直接写上的数字,没有小数点。例如:100、200、0、-250
  3. 浮点数常量:直接写上的数字,有小数点。例如:2.5、-3.14、0.0
  4. 字符常量:凡是用单引号引起来的单个字符,就做字符常量。例如:’A’、’b’、’9’、’中’
  5. 布尔常量:只有量中取值。true、false。
  6. 空常量:null。代表没有任何数据。

变量:程序运行期间,内容可以发生改变的量。

创建一个变量并且使用的格式:

1
2
3
4
数据类型 变量名称; // 创建了一个变量
变量名称 = 数据值; // 赋值,将右边的数据值,赋值交给左边的变量
一步到位的格式:
数据类型 变量名称 = 数据值; // 在创建一个变量的同时,立刻放入指定的数据值

创建一个变量

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
// 格式:数据类型 变量名称;
int num1;
// 向变量当中存入一个数据
// 格式:变量名称 = 数据值;
num1 = 10;
// 当打印输出变量名称的时候,显示出来的是变量的内容
System.out.println(num1); // 10

// 改变变量当中本来的数字,变成新的数字
num1 = 20;
System.out.println(num1); // 20

// 使用一步到位的格式来定义变量
// 格式:数据类型 变量名称 = 数据值;
int num2 = 25;
System.out.println(num2); // 25

num2 = 35;
System.out.println(num2); // 35
System.out.println("===============");

byte num3 = 30; // 注意:右侧数值的范围不能超过左侧数据类型的取值范围
System.out.println(num3); // 30

// byte num4 = 400; // 右侧超出了byte数据范围,错误!

short num5 = 50;
System.out.println(num5); // 50

long num6 = 3000000000L;
System.out.println(num6); // 3000000000

float num7 = 2.5F;
System.out.println(num7); // 2.5

double num8 = 1.2;
System.out.println(num8); // 1.2

char zifu1 = 'A';
System.out.println(zifu1); // A

zifu1 = '中';
System.out.println(zifu1); // 中

boolean var1 = true;
System.out.println(var1); // true

var1 = false;
System.out.println(var1); // false

// 将一个变量的数据内容,赋值交给另一个变量
// 右侧的变量名称var1已经存在,里面装的是false布尔值
// 将右侧变量里面的false值,向左交给var2变量进行存储
boolean var2 = var1;
System.out.println(var2); // false

分支语句

if / else

1
2
3
4
5
6
7
8
// 标准 if-else 语句
int num = 666;

if (num % 2 == 0) { // 如果除以2能够余数为0,说明是偶数
System.out.println("偶数");
} else {
System.out.println("奇数");
}

switch

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int num = 2;
switch (num) {
case 1:
System.out.println("你好");
break;
case 2:
System.out.println("我好");
// break;
case 3:
System.out.println("大家好");
break;
default:
System.out.println("他好,我也好。");
break;

循环语句

for

1
2
3
for (int i = 1; i <= 100; i++) {
System.out.println("我错啦!原谅我吧!" + i);
}

while

1
2
3
4
5
int i = 1; // 1. 初始化语句
while (i <= 10) { // 2. 条件判断
System.out.println("我错啦!" + i); // 3. 循环体
i++; // 4. 步进语句
}

同类事物的抽象描述

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Student {

// 成员变量
String name; // 姓名
int age; // 姓名

// 成员方法
public void eat() {
System.out.println("吃饭饭!");
}

public void sleep() {
System.out.println("睡觉觉!");
}

public void study() {
System.out.println("学习!");
}
}

代码参考