8030851: Update code in java.util to use newer language features

Reviewed-by: dfuchs, briangoetz, chegar, alanb, mduigou
This commit is contained in:
Paul Sandoz 2013-12-20 13:38:13 +01:00
parent 3cb52c1acc
commit f35ec148f5
37 changed files with 215 additions and 258 deletions

View File

@ -448,13 +448,11 @@ public abstract class AbstractMap<K,V> implements Map<K,V> {
return false;
try {
Iterator<Entry<K,V>> i = entrySet().iterator();
while (i.hasNext()) {
Entry<K,V> e = i.next();
for (Entry<K, V> e : entrySet()) {
K key = e.getKey();
V value = e.getValue();
if (value == null) {
if (!(m.get(key)==null && m.containsKey(key)))
if (!(m.get(key) == null && m.containsKey(key)))
return false;
} else {
if (!value.equals(m.get(key)))
@ -489,9 +487,8 @@ public abstract class AbstractMap<K,V> implements Map<K,V> {
*/
public int hashCode() {
int h = 0;
Iterator<Entry<K,V>> i = entrySet().iterator();
while (i.hasNext())
h += i.next().hashCode();
for (Entry<K, V> entry : entrySet())
h += entry.hashCode();
return h;
}

View File

@ -213,9 +213,8 @@ public abstract class AbstractSequentialList<E> extends AbstractList<E> {
try {
boolean modified = false;
ListIterator<E> e1 = listIterator(index);
Iterator<? extends E> e2 = c.iterator();
while (e2.hasNext()) {
e1.add(e2.next());
for (E e : c) {
e1.add(e);
modified = true;
}
return modified;

View File

@ -170,8 +170,8 @@ public abstract class AbstractSet<E> extends AbstractCollection<E> implements Se
boolean modified = false;
if (size() > c.size()) {
for (Iterator<?> i = c.iterator(); i.hasNext(); )
modified |= remove(i.next());
for (Object e : c)
modified |= remove(e);
} else {
for (Iterator<?> i = iterator(); i.hasNext(); ) {
if (c.contains(i.next())) {

View File

@ -902,7 +902,7 @@ public class ArrayDeque<E> extends AbstractCollection<E>
* @since 1.8
*/
public Spliterator<E> spliterator() {
return new DeqSpliterator<E>(this, -1, -1);
return new DeqSpliterator<>(this, -1, -1);
}
static final class DeqSpliterator<E> implements Spliterator<E> {

View File

@ -1218,8 +1218,8 @@ public class ArrayList<E> extends AbstractList<E>
public Spliterator<E> spliterator() {
checkForComodification();
return new ArrayListSpliterator<E>(ArrayList.this, offset,
offset + this.size, this.modCount);
return new ArrayListSpliterator<>(ArrayList.this, offset,
offset + this.size, this.modCount);
}
}
@ -1322,8 +1322,8 @@ public class ArrayList<E> extends AbstractList<E>
public ArrayListSpliterator<E> trySplit() {
int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
return (lo >= mid) ? null : // divide range in half unless too small
new ArrayListSpliterator<E>(list, lo, index = mid,
expectedModCount);
new ArrayListSpliterator<>(list, lo, index = mid,
expectedModCount);
}
public boolean tryAdvance(Consumer<? super E> action) {

View File

@ -142,9 +142,9 @@ class ArrayPrefixHelpers {
if (lt == null) { // first pass
int mid = (l + h) >>> 1;
f = rt = t.right =
new CumulateTask<T>(t, fn, a, org, fnc, th, mid, h);
new CumulateTask<>(t, fn, a, org, fnc, th, mid, h);
t = lt = t.left =
new CumulateTask<T>(t, fn, a, org, fnc, th, l, mid);
new CumulateTask<>(t, fn, a, org, fnc, th, l, mid);
}
else { // possibly refork
T pin = t.in;

View File

@ -1002,7 +1002,7 @@ public class Arrays {
(p = ForkJoinPool.getCommonPoolParallelism()) == 1)
TimSort.sort(a, 0, n, NaturalOrder.INSTANCE, null, 0, 0);
else
new ArraysParallelSortHelpers.FJObject.Sorter<T>
new ArraysParallelSortHelpers.FJObject.Sorter<>
(null, a,
(T[])Array.newInstance(a.getClass().getComponentType(), n),
0, n, 0, ((g = n / (p << 2)) <= MIN_ARRAY_SORT_GRAN) ?
@ -1061,7 +1061,7 @@ public class Arrays {
(p = ForkJoinPool.getCommonPoolParallelism()) == 1)
TimSort.sort(a, fromIndex, toIndex, NaturalOrder.INSTANCE, null, 0, 0);
else
new ArraysParallelSortHelpers.FJObject.Sorter<T>
new ArraysParallelSortHelpers.FJObject.Sorter<>
(null, a,
(T[])Array.newInstance(a.getClass().getComponentType(), n),
fromIndex, n, 0, ((g = n / (p << 2)) <= MIN_ARRAY_SORT_GRAN) ?
@ -1110,7 +1110,7 @@ public class Arrays {
(p = ForkJoinPool.getCommonPoolParallelism()) == 1)
TimSort.sort(a, 0, n, cmp, null, 0, 0);
else
new ArraysParallelSortHelpers.FJObject.Sorter<T>
new ArraysParallelSortHelpers.FJObject.Sorter<>
(null, a,
(T[])Array.newInstance(a.getClass().getComponentType(), n),
0, n, 0, ((g = n / (p << 2)) <= MIN_ARRAY_SORT_GRAN) ?
@ -1171,7 +1171,7 @@ public class Arrays {
(p = ForkJoinPool.getCommonPoolParallelism()) == 1)
TimSort.sort(a, fromIndex, toIndex, cmp, null, 0, 0);
else
new ArraysParallelSortHelpers.FJObject.Sorter<T>
new ArraysParallelSortHelpers.FJObject.Sorter<>
(null, a,
(T[])Array.newInstance(a.getClass().getComponentType(), n),
fromIndex, n, 0, ((g = n / (p << 2)) <= MIN_ARRAY_SORT_GRAN) ?
@ -4587,7 +4587,7 @@ public class Arrays {
if (a.length != 0 && bufLen <= 0)
bufLen = Integer.MAX_VALUE;
StringBuilder buf = new StringBuilder(bufLen);
deepToString(a, buf, new HashSet<Object[]>());
deepToString(a, buf, new HashSet<>());
return buf.toString();
}

View File

@ -130,15 +130,15 @@ import java.util.concurrent.CountedCompleter;
int b = this.base, n = this.size, wb = this.wbase, g = this.gran;
while (n > g) {
int h = n >>> 1, q = h >>> 1, u = h + q; // quartiles
Relay fc = new Relay(new Merger<T>(s, w, a, wb, h,
wb+h, n-h, b, g, c));
Relay rc = new Relay(new Merger<T>(fc, a, w, b+h, q,
b+u, n-u, wb+h, g, c));
new Sorter<T>(rc, a, w, b+u, n-u, wb+u, g, c).fork();
new Sorter<T>(rc, a, w, b+h, q, wb+h, g, c).fork();;
Relay bc = new Relay(new Merger<T>(fc, a, w, b, q,
b+q, h-q, wb, g, c));
new Sorter<T>(bc, a, w, b+q, h-q, wb+q, g, c).fork();
Relay fc = new Relay(new Merger<>(s, w, a, wb, h,
wb+h, n-h, b, g, c));
Relay rc = new Relay(new Merger<>(fc, a, w, b+h, q,
b+u, n-u, wb+h, g, c));
new Sorter<>(rc, a, w, b+u, n-u, wb+u, g, c).fork();
new Sorter<>(rc, a, w, b+h, q, wb+h, g, c).fork();;
Relay bc = new Relay(new Merger<>(fc, a, w, b, q,
b+q, h-q, wb, g, c));
new Sorter<>(bc, a, w, b+q, h-q, wb+q, g, c).fork();
s = new EmptyCompleter(bc);
n = q;
}
@ -199,9 +199,9 @@ import java.util.concurrent.CountedCompleter;
lo = lm + 1;
}
}
Merger<T> m = new Merger<T>(this, a, w, lb + lh, ln - lh,
rb + rh, rn - rh,
k + lh + rh, g, c);
Merger<T> m = new Merger<>(this, a, w, lb + lh, ln - lh,
rb + rh, rn - rh,
k + lh + rh, g, c);
rn = rh;
ln = lh;
addToPendingCount(1);

View File

@ -3380,8 +3380,7 @@ public abstract class Calendar implements Serializable, Cloneable, Comparable<Ca
for (;;) {
int min = Integer.MAX_VALUE;
for (int i = 0; i < stamp.length; i++) {
int v = stamp[i];
for (int v : stamp) {
if (v >= newStamp && min > v) {
min = v;
}

View File

@ -165,9 +165,9 @@ public class Collections {
Object[] a = list.toArray();
Arrays.sort(a);
ListIterator<T> i = list.listIterator();
for (int j=0; j<a.length; j++) {
for (Object e : a) {
i.next();
i.set((T)a[j]);
i.set((T) e);
}
}
@ -229,9 +229,9 @@ public class Collections {
Object[] a = list.toArray();
Arrays.sort(a, (Comparator)c);
ListIterator<T> i = list.listIterator();
for (int j=0; j<a.length; j++) {
for (Object e : a) {
i.next();
i.set((T)a[j]);
i.set((T) e);
}
}
@ -528,9 +528,9 @@ public class Collections {
// the wildcard but it will require a call to a supplementary
// private method
ListIterator it = list.listIterator();
for (int i=0; i<arr.length; i++) {
for (Object e : arr) {
it.next();
it.set(arr[i]);
it.set(e);
}
}
}
@ -1283,7 +1283,7 @@ public class Collections {
private static final long serialVersionUID = -6291252904449939134L;
public EmptyNavigableSet() {
super(new TreeSet<E>());
super(new TreeSet<>());
}
private Object readResolve() { return EMPTY_NAVIGABLE_SET; }
@ -1910,7 +1910,7 @@ public class Collections {
private static final long serialVersionUID = -2239321462712562324L;
EmptyNavigableMap() { super(new TreeMap<K,V>()); }
EmptyNavigableMap() { super(new TreeMap<>()); }
@Override
public NavigableSet<K> navigableKeySet()

View File

@ -2499,8 +2499,7 @@ public final class Formatter implements Closeable, Flushable {
int lasto = -1;
FormatString[] fsa = parse(format);
for (int i = 0; i < fsa.length; i++) {
FormatString fs = fsa[i];
for (FormatString fs : fsa) {
int index = fs.index();
try {
switch (index) {
@ -2992,9 +2991,9 @@ public final class Formatter implements Closeable, Flushable {
}
private void checkBadFlags(Flags ... badFlags) {
for (int i = 0; i < badFlags.length; i++)
if (f.contains(badFlags[i]))
failMismatch(badFlags[i], c);
for (Flags badFlag : badFlags)
if (f.contains(badFlag))
failMismatch(badFlag, c);
}
private void checkFloat() {
@ -4437,8 +4436,8 @@ public final class Formatter implements Closeable, Flushable {
public static Flags parse(String s) {
char[] ca = s.toCharArray();
Flags f = new Flags(0);
for (int i = 0; i < ca.length; i++) {
Flags v = parse(ca[i]);
for (char c : ca) {
Flags v = parse(c);
if (f.contains(v))
throw new DuplicateFormatFlagsException(v.toString());
f.add(v);

View File

@ -344,13 +344,13 @@ public class HashMap<K,V> extends AbstractMap<K,V>
*/
static Class<?> comparableClassFor(Object x) {
if (x instanceof Comparable) {
Class<?> c; Type[] ts, as; Type t; ParameterizedType p;
Class<?> c; Type[] ts, as; ParameterizedType p;
if ((c = x.getClass()) == String.class) // bypass checks
return c;
if ((ts = c.getGenericInterfaces()) != null) {
for (int i = 0; i < ts.length; ++i) {
if (((t = ts[i]) instanceof ParameterizedType) &&
((p = (ParameterizedType)t).getRawType() ==
for (Type t : ts) {
if ((t instanceof ParameterizedType) &&
((p = (ParameterizedType) t).getRawType() ==
Comparable.class) &&
(as = p.getActualTypeArguments()) != null &&
as.length == 1 && as[0] == c) // type arg is c
@ -875,8 +875,8 @@ public class HashMap<K,V> extends AbstractMap<K,V>
public boolean containsValue(Object value) {
Node<K,V>[] tab; V v;
if ((tab = table) != null && size > 0) {
for (int i = 0; i < tab.length; ++i) {
for (Node<K,V> e = tab[i]; e != null; e = e.next) {
for (Node<K, V> e : tab) {
for (; e != null; e = e.next) {
if ((v = e.value) == value ||
(value != null && value.equals(v)))
return true;
@ -923,8 +923,8 @@ public class HashMap<K,V> extends AbstractMap<K,V>
throw new NullPointerException();
if (size > 0 && (tab = table) != null) {
int mc = modCount;
for (int i = 0; i < tab.length; ++i) {
for (Node<K,V> e = tab[i]; e != null; e = e.next)
for (Node<K, V> e : tab) {
for (; e != null; e = e.next)
action.accept(e.key);
}
if (modCount != mc)
@ -967,8 +967,8 @@ public class HashMap<K,V> extends AbstractMap<K,V>
throw new NullPointerException();
if (size > 0 && (tab = table) != null) {
int mc = modCount;
for (int i = 0; i < tab.length; ++i) {
for (Node<K,V> e = tab[i]; e != null; e = e.next)
for (Node<K, V> e : tab) {
for (; e != null; e = e.next)
action.accept(e.value);
}
if (modCount != mc)
@ -1030,8 +1030,8 @@ public class HashMap<K,V> extends AbstractMap<K,V>
throw new NullPointerException();
if (size > 0 && (tab = table) != null) {
int mc = modCount;
for (int i = 0; i < tab.length; ++i) {
for (Node<K,V> e = tab[i]; e != null; e = e.next)
for (Node<K, V> e : tab) {
for (; e != null; e = e.next)
action.accept(e);
}
if (modCount != mc)
@ -1275,8 +1275,8 @@ public class HashMap<K,V> extends AbstractMap<K,V>
throw new NullPointerException();
if (size > 0 && (tab = table) != null) {
int mc = modCount;
for (int i = 0; i < tab.length; ++i) {
for (Node<K,V> e = tab[i]; e != null; e = e.next)
for (Node<K, V> e : tab) {
for (; e != null; e = e.next)
action.accept(e.key, e.value);
}
if (modCount != mc)
@ -1291,8 +1291,8 @@ public class HashMap<K,V> extends AbstractMap<K,V>
throw new NullPointerException();
if (size > 0 && (tab = table) != null) {
int mc = modCount;
for (int i = 0; i < tab.length; ++i) {
for (Node<K,V> e = tab[i]; e != null; e = e.next) {
for (Node<K, V> e : tab) {
for (; e != null; e = e.next) {
e.value = function.apply(e.key, e.value);
}
}
@ -1771,8 +1771,8 @@ public class HashMap<K,V> extends AbstractMap<K,V>
void internalWriteEntries(java.io.ObjectOutputStream s) throws IOException {
Node<K,V>[] tab;
if (size > 0 && (tab = table) != null) {
for (int i = 0; i < tab.length; ++i) {
for (Node<K,V> e = tab[i]; e != null; e = e.next) {
for (Node<K, V> e : tab) {
for (; e != null; e = e.next) {
s.writeObject(e.key);
s.writeObject(e.value);
}

View File

@ -324,8 +324,8 @@ public class HashSet<E>
// Create backing HashMap
map = (((HashSet<?>)this) instanceof LinkedHashSet ?
new LinkedHashMap<E,Object>(capacity, loadFactor) :
new HashMap<E,Object>(capacity, loadFactor));
new LinkedHashMap<>(capacity, loadFactor) :
new HashMap<>(capacity, loadFactor));
// Read in all elements in the proper order.
for (int i=0; i<size; i++) {
@ -348,6 +348,6 @@ public class HashSet<E>
* @since 1.8
*/
public Spliterator<E> spliterator() {
return new HashMap.KeySpliterator<E,Object>(map, 0, -1, 0, 0);
return new HashMap.KeySpliterator<>(map, 0, -1, 0, 0);
}
}

View File

@ -801,13 +801,11 @@ public class Hashtable<K,V>
return false;
try {
Iterator<Map.Entry<K,V>> i = entrySet().iterator();
while (i.hasNext()) {
Map.Entry<K,V> e = i.next();
for (Map.Entry<K, V> e : entrySet()) {
K key = e.getKey();
V value = e.getValue();
if (value == null) {
if (!(t.get(key)==null && t.containsKey(key)))
if (!(t.get(key) == null && t.containsKey(key)))
return false;
} else {
if (!value.equals(t.get(key)))
@ -1140,8 +1138,7 @@ public class Hashtable<K,V>
s.writeInt(count);
// Stack copies of the entries in the table
for (int index = 0; index < table.length; index++) {
Entry<?,?> entry = table[index];
for (Entry<?, ?> entry : table) {
while (entry != null) {
entryStack =

View File

@ -1426,8 +1426,8 @@ public class IdentityHashMap<K,V>
public KeySpliterator<K,V> trySplit() {
int hi = getFence(), lo = index, mid = ((lo + hi) >>> 1) & ~1;
return (lo >= mid) ? null :
new KeySpliterator<K,V>(map, lo, index = mid, est >>>= 1,
expectedModCount);
new KeySpliterator<>(map, lo, index = mid, est >>>= 1,
expectedModCount);
}
@SuppressWarnings("unchecked")
@ -1483,8 +1483,8 @@ public class IdentityHashMap<K,V>
public ValueSpliterator<K,V> trySplit() {
int hi = getFence(), lo = index, mid = ((lo + hi) >>> 1) & ~1;
return (lo >= mid) ? null :
new ValueSpliterator<K,V>(map, lo, index = mid, est >>>= 1,
expectedModCount);
new ValueSpliterator<>(map, lo, index = mid, est >>>= 1,
expectedModCount);
}
public void forEachRemaining(Consumer<? super V> action) {
@ -1542,8 +1542,8 @@ public class IdentityHashMap<K,V>
public EntrySpliterator<K,V> trySplit() {
int hi = getFence(), lo = index, mid = ((lo + hi) >>> 1) & ~1;
return (lo >= mid) ? null :
new EntrySpliterator<K,V>(map, lo, index = mid, est >>>= 1,
expectedModCount);
new EntrySpliterator<>(map, lo, index = mid, est >>>= 1,
expectedModCount);
}
public void forEachRemaining(Consumer<? super Map.Entry<K, V>> action) {
@ -1560,7 +1560,7 @@ public class IdentityHashMap<K,V>
(K)unmaskNull(key);
@SuppressWarnings("unchecked") V v = (V)a[i+1];
action.accept
(new AbstractMap.SimpleImmutableEntry<K,V>(k, v));
(new AbstractMap.SimpleImmutableEntry<>(k, v));
}
}
@ -1583,7 +1583,7 @@ public class IdentityHashMap<K,V>
@SuppressWarnings("unchecked") K k =
(K)unmaskNull(key);
action.accept
(new AbstractMap.SimpleImmutableEntry<K,V>(k, v));
(new AbstractMap.SimpleImmutableEntry<>(k, v));
if (map.modCount != expectedModCount)
throw new ConcurrentModificationException();
return true;

View File

@ -254,7 +254,7 @@ public class LinkedHashMap<K,V>
Node<K,V> newNode(int hash, K key, V value, Node<K,V> e) {
LinkedHashMap.Entry<K,V> p =
new LinkedHashMap.Entry<K,V>(hash, key, value, e);
new LinkedHashMap.Entry<>(hash, key, value, e);
linkNodeLast(p);
return p;
}
@ -262,20 +262,20 @@ public class LinkedHashMap<K,V>
Node<K,V> replacementNode(Node<K,V> p, Node<K,V> next) {
LinkedHashMap.Entry<K,V> q = (LinkedHashMap.Entry<K,V>)p;
LinkedHashMap.Entry<K,V> t =
new LinkedHashMap.Entry<K,V>(q.hash, q.key, q.value, next);
new LinkedHashMap.Entry<>(q.hash, q.key, q.value, next);
transferLinks(q, t);
return t;
}
TreeNode<K,V> newTreeNode(int hash, K key, V value, Node<K,V> next) {
TreeNode<K,V> p = new TreeNode<K,V>(hash, key, value, next);
TreeNode<K,V> p = new TreeNode<>(hash, key, value, next);
linkNodeLast(p);
return p;
}
TreeNode<K,V> replacementTreeNode(Node<K,V> p, Node<K,V> next) {
LinkedHashMap.Entry<K,V> q = (LinkedHashMap.Entry<K,V>)p;
TreeNode<K,V> t = new TreeNode<K,V>(q.hash, q.key, q.value, next);
TreeNode<K,V> t = new TreeNode<>(q.hash, q.key, q.value, next);
transferLinks(q, t);
return t;
}

View File

@ -1167,7 +1167,7 @@ public class LinkedList<E>
*/
@Override
public Spliterator<E> spliterator() {
return new LLSpliterator<E>(this, -1, 0);
return new LLSpliterator<>(this, -1, 0);
}
/** A customized variant of Spliterators.IteratorSpliterator */

View File

@ -194,10 +194,10 @@ public abstract class ListResourceBundle extends ResourceBundle {
Object[][] contents = getContents();
HashMap<String,Object> temp = new HashMap<>(contents.length);
for (int i = 0; i < contents.length; ++i) {
for (Object[] content : contents) {
// key must be non-null String, value must be non-null
String key = (String) contents[i][0];
Object value = contents[i][1];
String key = (String) content[0];
Object value = content[1];
if (key == null || value == null) {
throw new NullPointerException();
}

View File

@ -258,8 +258,8 @@ public class PriorityQueue<E> extends AbstractQueue<E>
a = Arrays.copyOf(a, a.length, Object[].class);
int len = a.length;
if (len == 1 || this.comparator != null)
for (int i = 0; i < len; i++)
if (a[i] == null)
for (Object e : a)
if (e == null)
throw new NullPointerException();
this.queue = a;
this.size = a.length;
@ -809,7 +809,7 @@ public class PriorityQueue<E> extends AbstractQueue<E>
* @since 1.8
*/
public final Spliterator<E> spliterator() {
return new PriorityQueueSpliterator<E>(this, 0, -1, 0);
return new PriorityQueueSpliterator<>(this, 0, -1, 0);
}
static final class PriorityQueueSpliterator<E> implements Spliterator<E> {
@ -843,8 +843,8 @@ public class PriorityQueue<E> extends AbstractQueue<E>
public PriorityQueueSpliterator<E> trySplit() {
int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
return (lo >= mid) ? null :
new PriorityQueueSpliterator<E>(pq, lo, index = mid,
expectedModCount);
new PriorityQueueSpliterator<>(pq, lo, index = mid,
expectedModCount);
}
@SuppressWarnings("unchecked")

View File

@ -1494,19 +1494,15 @@ public abstract class ResourceBundle {
Locale targetLocale = cacheKey.getLocale();
ResourceBundle bundle = null;
int size = formats.size();
for (int i = 0; i < size; i++) {
String format = formats.get(i);
for (String format : formats) {
try {
bundle = control.newBundle(cacheKey.getName(), targetLocale, format,
cacheKey.getLoader(), reload);
} catch (LinkageError error) {
} catch (LinkageError | Exception error) {
// We need to handle the LinkageError case due to
// inconsistent case-sensitivity in ClassLoader.
// See 6572242 for details.
cacheKey.setCause(error);
} catch (Exception cause) {
cacheKey.setCause(cause);
}
if (bundle != null) {
// Set the format in the cache key so that it can be

View File

@ -297,8 +297,8 @@ class StringTokenizer implements Enumeration<Object> {
}
private boolean isDelimiter(int codePoint) {
for (int i = 0; i < delimiterCodePoints.length; i++) {
if (delimiterCodePoints[i] == codePoint) {
for (int delimiterCodePoint : delimiterCodePoints) {
if (delimiterCodePoint == codePoint) {
return true;
}
}

View File

@ -198,8 +198,7 @@ public class TreeMap<K,V>
comparator = m.comparator();
try {
buildFromSorted(m.size(), m.entrySet().iterator(), null, null);
} catch (java.io.IOException cannotHappen) {
} catch (ClassNotFoundException cannotHappen) {
} catch (java.io.IOException | ClassNotFoundException cannotHappen) {
}
}
@ -318,8 +317,7 @@ public class TreeMap<K,V>
try {
buildFromSorted(mapSize, map.entrySet().iterator(),
null, null);
} catch (java.io.IOException cannotHappen) {
} catch (ClassNotFoundException cannotHappen) {
} catch (java.io.IOException | ClassNotFoundException cannotHappen) {
}
return;
}
@ -644,8 +642,7 @@ public class TreeMap<K,V>
// Initialize clone with our mappings
try {
clone.buildFromSorted(size, entrySet().iterator(), null, null);
} catch (java.io.IOException cannotHappen) {
} catch (ClassNotFoundException cannotHappen) {
} catch (java.io.IOException | ClassNotFoundException cannotHappen) {
}
return clone;
@ -1050,7 +1047,7 @@ public class TreeMap<K,V>
}
public Spliterator<V> spliterator() {
return new ValueSpliterator<K,V>(TreeMap.this, null, null, 0, -1, 0);
return new ValueSpliterator<>(TreeMap.this, null, null, 0, -1, 0);
}
}
@ -1090,7 +1087,7 @@ public class TreeMap<K,V>
}
public Spliterator<Map.Entry<K,V>> spliterator() {
return new EntrySpliterator<K,V>(TreeMap.this, null, null, 0, -1, 0);
return new EntrySpliterator<>(TreeMap.this, null, null, 0, -1, 0);
}
}
@ -2427,8 +2424,7 @@ public class TreeMap<K,V>
s.writeInt(size);
// Write out keys and values (alternating)
for (Iterator<Map.Entry<K,V>> i = entrySet().iterator(); i.hasNext(); ) {
Map.Entry<K,V> e = i.next();
for (Map.Entry<K, V> e : entrySet()) {
s.writeObject(e.getKey());
s.writeObject(e.getValue());
}
@ -2459,8 +2455,7 @@ public class TreeMap<K,V>
void addAllForTreeSet(SortedSet<? extends K> set, V defaultVal) {
try {
buildFromSorted(set.size(), set.iterator(), null, defaultVal);
} catch (java.io.IOException cannotHappen) {
} catch (ClassNotFoundException cannotHappen) {
} catch (java.io.IOException | ClassNotFoundException cannotHappen) {
}
}
@ -2631,11 +2626,11 @@ public class TreeMap<K,V>
}
final Spliterator<K> keySpliterator() {
return new KeySpliterator<K,V>(this, null, null, 0, -1, 0);
return new KeySpliterator<>(this, null, null, 0, -1, 0);
}
final Spliterator<K> descendingKeySpliterator() {
return new DescendingKeySpliterator<K,V>(this, null, null, 0, -2, 0);
return new DescendingKeySpliterator<>(this, null, null, 0, -2, 0);
}
/**

View File

@ -121,7 +121,7 @@ public class TreeSet<E> extends AbstractSet<E>
* {@code ClassCastException}.
*/
public TreeSet() {
this(new TreeMap<E,Object>());
this(new TreeMap<>());
}
/**

View File

@ -1374,8 +1374,8 @@ public class Vector<E>
public Spliterator<E> trySplit() {
int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
return (lo >= mid) ? null :
new VectorSpliterator<E>(list, array, lo, index = mid,
expectedModCount);
new VectorSpliterator<>(list, array, lo, index = mid,
expectedModCount);
}
@SuppressWarnings("unchecked")

View File

@ -1097,8 +1097,8 @@ public class WeakHashMap<K,V>
public KeySpliterator<K,V> trySplit() {
int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
return (lo >= mid) ? null :
new KeySpliterator<K,V>(map, lo, index = mid, est >>>= 1,
expectedModCount);
new KeySpliterator<>(map, lo, index = mid, est >>>= 1,
expectedModCount);
}
public void forEachRemaining(Consumer<? super K> action) {
@ -1177,8 +1177,8 @@ public class WeakHashMap<K,V>
public ValueSpliterator<K,V> trySplit() {
int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
return (lo >= mid) ? null :
new ValueSpliterator<K,V>(map, lo, index = mid, est >>>= 1,
expectedModCount);
new ValueSpliterator<>(map, lo, index = mid, est >>>= 1,
expectedModCount);
}
public void forEachRemaining(Consumer<? super V> action) {
@ -1254,8 +1254,8 @@ public class WeakHashMap<K,V>
public EntrySpliterator<K,V> trySplit() {
int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
return (lo >= mid) ? null :
new EntrySpliterator<K,V>(map, lo, index = mid, est >>>= 1,
expectedModCount);
new EntrySpliterator<>(map, lo, index = mid, est >>>= 1,
expectedModCount);
}
@ -1286,7 +1286,7 @@ public class WeakHashMap<K,V>
@SuppressWarnings("unchecked") K k =
(K) WeakHashMap.unmaskNull(x);
action.accept
(new AbstractMap.SimpleImmutableEntry<K,V>(k, v));
(new AbstractMap.SimpleImmutableEntry<>(k, v));
}
}
} while (p != null || i < hi);
@ -1312,7 +1312,7 @@ public class WeakHashMap<K,V>
@SuppressWarnings("unchecked") K k =
(K) WeakHashMap.unmaskNull(x);
action.accept
(new AbstractMap.SimpleImmutableEntry<K,V>(k, v));
(new AbstractMap.SimpleImmutableEntry<>(k, v));
if (map.modCount != expectedModCount)
throw new ConcurrentModificationException();
return true;

View File

@ -296,24 +296,22 @@ public class Attributes implements Map<Object,Object>, Cloneable {
* XXX Need to handle UTF8 values and break up lines longer than 72 bytes
*/
void write(DataOutputStream os) throws IOException {
Iterator<Map.Entry<Object, Object>> it = entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Object, Object> e = it.next();
StringBuffer buffer = new StringBuffer(
((Name)e.getKey()).toString());
buffer.append(": ");
for (Entry<Object, Object> e : entrySet()) {
StringBuffer buffer = new StringBuffer(
((Name) e.getKey()).toString());
buffer.append(": ");
String value = (String)e.getValue();
if (value != null) {
byte[] vb = value.getBytes("UTF8");
value = new String(vb, 0, 0, vb.length);
}
buffer.append(value);
String value = (String) e.getValue();
if (value != null) {
byte[] vb = value.getBytes("UTF8");
value = new String(vb, 0, 0, vb.length);
}
buffer.append(value);
buffer.append("\r\n");
Manifest.make72Safe(buffer);
os.writeBytes(buffer.toString());
}
buffer.append("\r\n");
Manifest.make72Safe(buffer);
os.writeBytes(buffer.toString());
}
os.writeBytes("\r\n");
}
@ -340,16 +338,14 @@ public class Attributes implements Map<Object,Object>, Cloneable {
// write out all attributes except for the version
// we wrote out earlier
Iterator<Map.Entry<Object, Object>> it = entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Object, Object> e = it.next();
String name = ((Name)e.getKey()).toString();
if ((version != null) && ! (name.equalsIgnoreCase(vername))) {
for (Entry<Object, Object> e : entrySet()) {
String name = ((Name) e.getKey()).toString();
if ((version != null) && !(name.equalsIgnoreCase(vername))) {
StringBuffer buffer = new StringBuffer(name);
buffer.append(": ");
String value = (String)e.getValue();
String value = (String) e.getValue();
if (value != null) {
byte[] vb = value.getBytes("UTF8");
value = new String(vb, 0, 0, vb.length);

View File

@ -324,8 +324,8 @@ class JarFile extends ZipFile {
if (verify) {
String[] names = getMetaInfEntryNames();
if (names != null) {
for (int i = 0; i < names.length; i++) {
String name = names[i].toUpperCase(Locale.ENGLISH);
for (String nameLower : names) {
String name = nameLower.toUpperCase(Locale.ENGLISH);
if (name.endsWith(".DSA") ||
name.endsWith(".RSA") ||
name.endsWith(".EC") ||
@ -356,8 +356,8 @@ class JarFile extends ZipFile {
try {
String[] names = getMetaInfEntryNames();
if (names != null) {
for (int i = 0; i < names.length; i++) {
JarEntry e = getJarEntry(names[i]);
for (String name : names) {
JarEntry e = getJarEntry(name);
if (e == null) {
throw new JarException("corrupted jar file");
}
@ -487,10 +487,9 @@ class JarFile extends ZipFile {
// entries to find a match.
String[] names = getMetaInfEntryNames();
if (names != null) {
for (int i = 0; i < names.length; i++) {
if (MANIFEST_NAME.equals(
names[i].toUpperCase(Locale.ENGLISH))) {
manEntry = getJarEntry(names[i]);
for (String name : names) {
if (MANIFEST_NAME.equals(name.toUpperCase(Locale.ENGLISH))) {
manEntry = getJarEntry(name);
break;
}
}
@ -580,11 +579,10 @@ class JarFile extends ZipFile {
}
String name = getName();
String localJavaHome = javaHome;
if (name.startsWith(localJavaHome)) {
if (name.startsWith(javaHome)) {
String[] names = jarNames;
for (int i = 0; i < names.length; i++) {
if (name.endsWith(names[i])) {
for (String jarName : names) {
if (name.endsWith(jarName)) {
return true;
}
}
@ -619,8 +617,8 @@ class JarFile extends ZipFile {
* code source?
*/
boolean includeUnsigned = false;
for (int i = 0; i < cs.length; i++) {
if (cs[i].getCodeSigners() == null) {
for (CodeSource c : cs) {
if (c.getCodeSigners() == null) {
includeUnsigned = true;
break;
}
@ -776,6 +774,6 @@ class JarFile extends ZipFile {
if (jv != null) {
return jv.getManifestDigests();
}
return new ArrayList<Object>();
return new ArrayList<>();
}
}

View File

@ -258,9 +258,7 @@ class JarVerifier {
sigFileData.put(key, bytes);
// check pending blocks, we can now process
// anyone waiting for this .SF file
Iterator<SignatureFileVerifier> it = pendingBlocks.iterator();
while (it.hasNext()) {
SignatureFileVerifier sfv = it.next();
for (SignatureFileVerifier sfv : pendingBlocks) {
if (sfv.needSignatureFile(key)) {
if (debug != null) {
debug.println(
@ -313,18 +311,9 @@ class JarVerifier {
}
sfv.process(sigFileSigners, manifestDigests);
} catch (IOException ioe) {
// e.g. sun.security.pkcs.ParsingException
if (debug != null) debug.println("processEntry caught: "+ioe);
// ignore and treat as unsigned
} catch (SignatureException se) {
if (debug != null) debug.println("processEntry caught: "+se);
// ignore and treat as unsigned
} catch (NoSuchAlgorithmException nsae) {
if (debug != null) debug.println("processEntry caught: "+nsae);
// ignore and treat as unsigned
} catch (CertificateException ce) {
if (debug != null) debug.println("processEntry caught: "+ce);
} catch (IOException | CertificateException |
NoSuchAlgorithmException | SignatureException e) {
if (debug != null) debug.println("processEntry caught: "+e);
// ignore and treat as unsigned
}
}
@ -387,9 +376,9 @@ class JarVerifier {
if (signers != null) {
ArrayList<java.security.cert.Certificate> certChains = new ArrayList<>();
for (int i = 0; i < signers.length; i++) {
for (CodeSigner signer : signers) {
certChains.addAll(
signers[i].getSignerCertPath().getCertificates());
signer.getSignerCertPath().getCertificates());
}
// Convert into a Certificate[]
@ -536,8 +525,8 @@ class JarVerifier {
private CodeSource[] mapSignersToCodeSources(URL url, List<CodeSigner[]> signers, boolean unsigned) {
List<CodeSource> sources = new ArrayList<>();
for (int i = 0; i < signers.size(); i++) {
sources.add(mapSignersToCodeSource(url, signers.get(i)));
for (CodeSigner[] signer : signers) {
sources.add(mapSignersToCodeSource(url, signer));
}
if (unsigned) {
sources.add(mapSignersToCodeSource(url, null));
@ -563,8 +552,8 @@ class JarVerifier {
*/
CodeSource[] sources = mapSignersToCodeSources(cs.getLocation(), getJarCodeSigners(), true);
List<CodeSource> sourceList = new ArrayList<>();
for (int i = 0; i < sources.length; i++) {
sourceList.add(sources[i]);
for (CodeSource source : sources) {
sourceList.add(source);
}
int j = sourceList.indexOf(cs);
if (j != -1) {
@ -677,8 +666,8 @@ class JarVerifier {
* to see if we can optimize CodeSigner equality test.
*/
List<CodeSigner[]> req = new ArrayList<>(cs.length);
for (int i = 0; i < cs.length; i++) {
CodeSigner[] match = findMatchingSigners(cs[i]);
for (CodeSource c : cs) {
CodeSigner[] match = findMatchingSigners(c);
if (match != null) {
if (match.length > 0) {
req.add(match);

View File

@ -148,9 +148,7 @@ public class Manifest implements Cloneable {
// Write out the main attributes for the manifest
attr.writeMain(dos);
// Now write out the pre-entry attributes
Iterator<Map.Entry<String, Attributes>> it = entries.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, Attributes> e = it.next();
for (Map.Entry<String, Attributes> e : entries.entrySet()) {
StringBuffer buffer = new StringBuffer("Name: ");
String value = e.getKey();
if (value != null) {

View File

@ -851,8 +851,7 @@ public class LogManager {
@Override
public Object run() {
String names[] = parseClassNames(handlersPropertyName);
for (int i = 0; i < names.length; i++) {
String word = names[i];
for (String word : names) {
try {
Class<?> clz = ClassLoader.getSystemClassLoader().loadClass(word);
Handler hdl = (Handler) clz.newInstance();
@ -1231,8 +1230,7 @@ public class LogManager {
private void resetLogger(Logger logger) {
// Close all the Logger's handlers.
Handler[] targets = logger.getHandlers();
for (int i = 0; i < targets.length; i++) {
Handler h = targets[i];
for (Handler h : targets) {
logger.removeHandler(h);
try {
h.close();
@ -1302,8 +1300,7 @@ public class LogManager {
// Instantiate new configuration objects.
String names[] = parseClassNames("config");
for (int i = 0; i < names.length; i++) {
String word = names[i];
for (String word : names) {
try {
Class<?> clz = ClassLoader.getSystemClassLoader().loadClass(word);
clz.newInstance();
@ -1489,9 +1486,7 @@ public class LogManager {
if (children == null) {
return;
}
Iterator<LogNode> values = children.values().iterator();
while (values.hasNext()) {
LogNode node = values.next();
for (LogNode node : children.values()) {
LoggerWeakRef ref = node.loggerRef;
Logger logger = (ref == null) ? null : ref.get();
if (logger == null) {

View File

@ -481,12 +481,8 @@ public class LogRecord implements java.io.Serializable {
}
out.writeInt(parameters.length);
// Write string values for the parameters.
for (int i = 0; i < parameters.length; i++) {
if (parameters[i] == null) {
out.writeObject(null);
} else {
out.writeObject(parameters[i].toString());
}
for (Object parameter : parameters) {
out.writeObject(Objects.toString(parameter, null));
}
}

View File

@ -2108,9 +2108,8 @@ public class Logger {
// Recursively update the level on each of our kids.
if (kids != null) {
for (int i = 0; i < kids.size(); i++) {
LogManager.LoggerWeakRef ref = kids.get(i);
Logger kid = ref.get();
for (LogManager.LoggerWeakRef ref : kids) {
Logger kid = ref.get();
if (kid != null) {
kid.updateEffectiveLevel();
}

View File

@ -173,12 +173,12 @@ public class XMLFormatter extends Formatter {
Object parameters[] = record.getParameters();
// Check to see if the parameter was not a messagetext format
// or was not null or empty
if ( parameters != null && parameters.length != 0
if (parameters != null && parameters.length != 0
&& record.getMessage().indexOf("{") == -1 ) {
for (int i = 0; i < parameters.length; i++) {
for (Object parameter : parameters) {
sb.append(" <param>");
try {
escape(sb, parameters[i].toString());
escape(sb, parameter.toString());
} catch (Exception ex) {
sb.append("???");
}
@ -194,8 +194,7 @@ public class XMLFormatter extends Formatter {
escape(sb, th.toString());
sb.append("</message>\n");
StackTraceElement trace[] = th.getStackTrace();
for (int i = 0; i < trace.length; i++) {
StackTraceElement frame = trace[i];
for (StackTraceElement frame : trace) {
sb.append(" <frame>\n");
sb.append(" <class>");
escape(sb, frame.getClassName());

View File

@ -334,9 +334,8 @@ public abstract class AbstractPreferences extends Preferences {
*/
public void clear() throws BackingStoreException {
synchronized(lock) {
String[] keys = keys();
for (int i=0; i<keys.length; i++)
remove(keys[i]);
for (String key : keys())
remove(key);
}
}
@ -959,9 +958,9 @@ public abstract class AbstractPreferences extends Preferences {
// Ensure that all children are cached
String[] kidNames = childrenNamesSpi();
for (int i=0; i<kidNames.length; i++)
if (!kidCache.containsKey(kidNames[i]))
kidCache.put(kidNames[i], childSpi(kidNames[i]));
for (String kidName : kidNames)
if (!kidCache.containsKey(kidName))
kidCache.put(kidName, childSpi(kidName));
// Recursively remove all cached children
for (Iterator<AbstractPreferences> i = kidCache.values().iterator();
@ -1257,9 +1256,9 @@ public abstract class AbstractPreferences extends Preferences {
synchronized(lock) {
// assert kidCache.get(nodeName)==null;
String[] kidNames = childrenNames();
for (int i=0; i<kidNames.length; i++)
if (kidNames[i].equals(nodeName))
return childSpi(kidNames[i]);
for (String kidName : kidNames)
if (kidName.equals(nodeName))
return childSpi(kidName);
}
return null;
}
@ -1339,8 +1338,8 @@ public abstract class AbstractPreferences extends Preferences {
cachedKids = cachedChildren();
}
for (int i=0; i<cachedKids.length; i++)
cachedKids[i].sync2();
for (AbstractPreferences cachedKid : cachedKids)
cachedKid.sync2();
}
/**
@ -1399,8 +1398,8 @@ public abstract class AbstractPreferences extends Preferences {
cachedKids = cachedChildren();
}
for (int i = 0; i < cachedKids.length; i++)
cachedKids[i].flush2();
for (AbstractPreferences cachedKid : cachedKids)
cachedKid.flush2();
}
/**
@ -1492,18 +1491,18 @@ public abstract class AbstractPreferences extends Preferences {
if (event instanceof PreferenceChangeEvent) {
PreferenceChangeEvent pce = (PreferenceChangeEvent)event;
PreferenceChangeListener[] listeners = src.prefListeners();
for (int i=0; i<listeners.length; i++)
listeners[i].preferenceChange(pce);
for (PreferenceChangeListener listener : listeners)
listener.preferenceChange(pce);
} else {
NodeChangeEvent nce = (NodeChangeEvent)event;
NodeChangeListener[] listeners = src.nodeListeners();
if (nce instanceof NodeAddedEvent) {
for (int i=0; i<listeners.length; i++)
listeners[i].childAdded(nce);
for (NodeChangeListener listener : listeners)
listener.childAdded(nce);
} else {
// assert nce instanceof NodeRemovedEvent;
for (int i=0; i<listeners.length; i++)
listeners[i].childRemoved(nce);
for (NodeChangeListener listener : listeners)
listener.childRemoved(nce);
}
}
}

View File

@ -154,12 +154,12 @@ class XmlSupport {
// Put map in xml element
String[] keys = prefs.keys();
Element map = (Element) elt.appendChild(doc.createElement("map"));
for (int i=0; i<keys.length; i++) {
for (String key : keys) {
Element entry = (Element)
map.appendChild(doc.createElement("entry"));
entry.setAttribute("key", keys[i]);
entry.setAttribute("key", key);
// NEXT STATEMENT THROWS NULL PTR EXC INSTEAD OF ASSERT FAIL
entry.setAttribute("value", prefs.get(keys[i], null));
entry.setAttribute("value", prefs.get(key, null));
}
// Recurse if appropriate
if (subTree) {
@ -344,8 +344,7 @@ class XmlSupport {
Element xmlMap = doc.getDocumentElement( ) ;
xmlMap.setAttribute("MAP_XML_VERSION", MAP_XML_VERSION);
for (Iterator<Map.Entry<String, String>> i = map.entrySet().iterator(); i.hasNext(); ) {
Map.Entry<String, String> e = i.next();
for (Map.Entry<String, String> e : map.entrySet()) {
Element xe = (Element)
xmlMap.appendChild(doc.createElement("entry"));
xe.setAttribute("key", e.getKey());

View File

@ -1545,8 +1545,8 @@ loop: for(int x=0, offset=0; x<nCodePoints; x++, offset+=len) {
String[] subResult = producePermutations(otherChars);
String prefix = input.substring(offset, offset+len);
for(int y=0; y<subResult.length; y++)
temp[index++] = prefix + subResult[y];
for (String sre : subResult)
temp[index++] = prefix + sre;
}
String[] result = new String[index];
for (int x=0; x<index; x++)
@ -2702,15 +2702,22 @@ loop: for(int x=0, offset=0; x<nCodePoints; x++, offset+=len) {
// property construct \p{name=value}
String value = name.substring(i + 1);
name = name.substring(0, i).toLowerCase(Locale.ENGLISH);
if ("sc".equals(name) || "script".equals(name)) {
node = unicodeScriptPropertyFor(value);
} else if ("blk".equals(name) || "block".equals(name)) {
node = unicodeBlockPropertyFor(value);
} else if ("gc".equals(name) || "general_category".equals(name)) {
node = charPropertyNodeFor(value);
} else {
throw error("Unknown Unicode property {name=<" + name + ">, "
+ "value=<" + value + ">}");
switch (name) {
case "sc":
case "script":
node = unicodeScriptPropertyFor(value);
break;
case "blk":
case "block":
node = unicodeBlockPropertyFor(value);
break;
case "gc":
case "general_category":
node = charPropertyNodeFor(value);
break;
default:
throw error("Unknown Unicode property {name=<" + name + ">, "
+ "value=<" + value + ">}");
}
} else {
if (name.startsWith("In")) {
@ -5497,8 +5504,8 @@ NEXT: while (i <= last) {
BnMS(int[] src, int[] lastOcc, int[] optoSft, Node next) {
super(src, lastOcc, optoSft, next);
for (int x = 0; x < buffer.length; x++) {
lengthInChars += Character.charCount(buffer[x]);
for (int cp : buffer) {
lengthInChars += Character.charCount(cp);
}
}
boolean match(Matcher matcher, int i, CharSequence seq) {

View File

@ -329,7 +329,7 @@ final class SortedOps {
public void begin(long size) {
if (size >= Nodes.MAX_ARRAY_SIZE)
throw new IllegalArgumentException(Nodes.BAD_SIZE);
list = (size >= 0) ? new ArrayList<T>((int) size) : new ArrayList<T>();
list = (size >= 0) ? new ArrayList<>((int) size) : new ArrayList<>();
}
@Override