Java Tutorial/Collections/Arrays Utilities
Содержание
- 1 Append the given Object to the given array
- 2 Array To String
- 3 Compare two byte type arrays
- 4 Compare two char type arrays
- 5 Compare two double type arrays
- 6 Compare two float type arrays
- 7 Compare two int type arrays
- 8 Compare two long type arrays
- 9 Compare two short type arrays
- 10 Convert an Array to a List
- 11 Convert the given array (which may be a primitive array) to an object array
- 12 Dump multi-dimensional arrays
- 13 Extend the size of an array
- 14 Filling Elements in an Array
- 15 filling object arrays:
- 16 fill to a contiguous range of elements in an array
- 17 Gets the subarray from array that starts at offset.
- 18 Gets the subarray of length length from array that starts at offset.
- 19 Growable String array with type specific access methods.
- 20 How to copy an array
- 21 How to sort an array
- 22 If the given objects are equal
- 23 Java Sort byte Array
- 24 Java Sort char Array
- 25 Java Sort double Array
- 26 Java Sort float Array
- 27 java.utils.Arrays provides ways to dump the content of an array.
- 28 Minimum and maximum number in array
- 29 Performing Binary Search on Java Array
- 30 Reverses the order of the given object array.
- 31 Shifting Elements in an Array: Shift all elements left by one
- 32 Shifting Elements in an Array: Shift all elements right by one
- 33 Shuffle elements of an array
- 34 Sort an array: case-insensitive
- 35 Sort an array: case-sensitive
- 36 Sorting an Array in Descending (Reverse) Order
- 37 Use java.util.Arrays.deepToString() to dump the multi-dimensional arrays
- 38 Wrapper for arrays of ordered strings. This verifies the arrays and supports efficient lookups.
Append the given Object to the given array
import java.lang.reflect.Array;
import java.util.Arrays;
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//Revised from springframework
/**
* Miscellaneous object utility methods. Mainly for internal use within the
* framework; consider Jakarta"s Commons Lang for a more comprehensive suite
* of object utilities.
*
* @author Juergen Hoeller
* @author Keith Donald
* @author Rod Johnson
* @author Rob Harrop
* @author Alex Ruiz
* @since 19.03.2004
* @see org.apache.rumons.lang.ObjectUtils
*/
abstract class ObjectUtils {
private static final int INITIAL_HASH = 7;
private static final int MULTIPLIER = 31;
private static final String EMPTY_STRING = "";
private static final String NULL_STRING = "null";
private static final String ARRAY_START = "{";
private static final String ARRAY_END = "}";
private static final String EMPTY_ARRAY = ARRAY_START + ARRAY_END;
private static final String ARRAY_ELEMENT_SEPARATOR = ", ";
/**
* Return whether the given array is empty: that is, <code>null</code>
* or of zero length.
* @param array the array to check
* @return whether the given array is empty
*/
public static boolean isEmpty(Object[] array) {
return (array == null || array.length == 0);
}
/**
* Append the given Object to the given array, returning a new array
* consisting of the input array contents plus the given Object.
* @param array the array to append to (can be <code>null</code>)
* @param obj the Object to append
* @return the new array (of the same component type; never <code>null</code>)
*/
public static Object[] addObjectToArray(Object[] array, Object obj) {
Class compType = Object.class;
if (array != null) {
compType = array.getClass().getComponentType();
}
else if (obj != null) {
compType = obj.getClass();
}
int newArrLength = (array != null ? array.length + 1 : 1);
Object[] newArr = (Object[]) Array.newInstance(compType, newArrLength);
if (array != null) {
System.arraycopy(array, 0, newArr, 0, array.length);
}
newArr[newArr.length - 1] = obj;
return newArr;
}
/**
* Convert the given array (which may be a primitive array) to an
* object array (if necessary of primitive wrapper objects).
* A <code>null</code> source value will be converted to an
* empty Object array.
* @param source the (potentially primitive) array
* @return the corresponding object array (never <code>null</code>)
* @throws IllegalArgumentException if the parameter is not an array
*/
public static Object[] toObjectArray(Object source) {
if (source instanceof Object[]) {
return (Object[]) source;
}
if (source == null) {
return new Object[0];
}
if (!source.getClass().isArray()) {
throw new IllegalArgumentException("Source is not an array: " + source);
}
int length = Array.getLength(source);
if (length == 0) {
return new Object[0];
}
Class wrapperType = Array.get(source, 0).getClass();
Object[] newArray = (Object[]) Array.newInstance(wrapperType, length);
for (int i = 0; i < length; i++) {
newArray[i] = Array.get(source, i);
}
return newArray;
}
}
Array To String
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.InetAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;
import java.util.Collection;
/**
* General string utils
*/
public class StringUtils {
final public static char COMMA = ",";
final public static String COMMA_STR = ",";
final public static char ESCAPE_CHAR = "\\";
private static DecimalFormat oneDecimal = new DecimalFormat("0.0");
/**
* Given an array of strings, return a comma-separated list of its elements.
* @param strs Array of strings
* @return Empty string if strs.length is 0, comma separated list of strings
* otherwise
*/
public static String arrayToString(String[] strs) {
if (strs.length == 0) { return ""; }
StringBuffer sbuf = new StringBuffer();
sbuf.append(strs[0]);
for (int idx = 1; idx < strs.length; idx++) {
sbuf.append(",");
sbuf.append(strs[idx]);
}
return sbuf.toString();
}
}
Compare two byte type arrays
import java.util.Arrays;
public class Main {
public static void main(String[] argv) throws Exception {
boolean b = Arrays.equals(new byte[] { 0 }, new byte[] { 0 }); // true
}
}
Compare two char type arrays
import java.util.Arrays;
public class Main {
public static void main(String[] argv) throws Exception {
boolean b = Arrays.equals(new char[] { "a" }, new char[] { "a" }); // true
}
}
Compare two double type arrays
import java.util.Arrays;
public class Main {
public static void main(String[] argv) throws Exception {
boolean b = Arrays.equals(new double[] { 0D }, new double[] { 0D }); // true
}
}
Compare two float type arrays
import java.util.Arrays;
public class Main {
public static void main(String[] argv) throws Exception {
boolean b = Arrays.equals(new float[] { 0F }, new float[] { 0F }); // true
}
}
Compare two int type arrays
import java.util.Arrays;
public class Main {
public static void main(String[] argv) throws Exception {
boolean b = Arrays.equals(new int[] { 0 }, new int[] { 0 }); // true
}
}
Compare two long type arrays
import java.util.Arrays;
public class Main {
public static void main(String[] argv) throws Exception {
boolean b = Arrays.equals(new long[] { 0L }, new long[] { 0L }); // true
}
}
Compare two short type arrays
import java.util.Arrays;
public class Main {
public static void main(String[] argv) throws Exception {
boolean b = Arrays.equals(new short[] { 0 }, new short[] { 0 }); // true
}
}
Convert an Array to a List
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
String[] cars = {"A", "B", "C", "D"};
List<String> carList = Arrays.asList(cars);
for (String car : carList) {
System.out.println(car);
}
}
}
Convert the given array (which may be a primitive array) to an object array
import java.lang.reflect.Array;
import java.util.Arrays;
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//Revised from springframework
/**
* Miscellaneous object utility methods. Mainly for internal use within the
* framework; consider Jakarta"s Commons Lang for a more comprehensive suite
* of object utilities.
*
* @author Juergen Hoeller
* @author Keith Donald
* @author Rod Johnson
* @author Rob Harrop
* @author Alex Ruiz
* @since 19.03.2004
* @see org.apache.rumons.lang.ObjectUtils
*/
abstract class ObjectUtils {
private static final int INITIAL_HASH = 7;
private static final int MULTIPLIER = 31;
private static final String EMPTY_STRING = "";
private static final String NULL_STRING = "null";
private static final String ARRAY_START = "{";
private static final String ARRAY_END = "}";
private static final String EMPTY_ARRAY = ARRAY_START + ARRAY_END;
private static final String ARRAY_ELEMENT_SEPARATOR = ", ";
/**
* Return whether the given array is empty: that is, <code>null</code>
* or of zero length.
* @param array the array to check
* @return whether the given array is empty
*/
public static boolean isEmpty(Object[] array) {
return (array == null || array.length == 0);
}
/**
* Append the given Object to the given array, returning a new array
* consisting of the input array contents plus the given Object.
* @param array the array to append to (can be <code>null</code>)
* @param obj the Object to append
* @return the new array (of the same component type; never <code>null</code>)
*/
public static Object[] addObjectToArray(Object[] array, Object obj) {
Class compType = Object.class;
if (array != null) {
compType = array.getClass().getComponentType();
}
else if (obj != null) {
compType = obj.getClass();
}
int newArrLength = (array != null ? array.length + 1 : 1);
Object[] newArr = (Object[]) Array.newInstance(compType, newArrLength);
if (array != null) {
System.arraycopy(array, 0, newArr, 0, array.length);
}
newArr[newArr.length - 1] = obj;
return newArr;
}
/**
* Convert the given array (which may be a primitive array) to an
* object array (if necessary of primitive wrapper objects).
* A <code>null</code> source value will be converted to an
* empty Object array.
* @param source the (potentially primitive) array
* @return the corresponding object array (never <code>null</code>)
* @throws IllegalArgumentException if the parameter is not an array
*/
public static Object[] toObjectArray(Object source) {
if (source instanceof Object[]) {
return (Object[]) source;
}
if (source == null) {
return new Object[0];
}
if (!source.getClass().isArray()) {
throw new IllegalArgumentException("Source is not an array: " + source);
}
int length = Array.getLength(source);
if (length == 0) {
return new Object[0];
}
Class wrapperType = Array.get(source, 0).getClass();
Object[] newArray = (Object[]) Array.newInstance(wrapperType, length);
for (int i = 0; i < length; i++) {
newArray[i] = Array.get(source, i);
}
return newArray;
}
}
Dump multi-dimensional arrays
import java.util.Arrays;
public class Main {
public static void main(String args[]) {
String s[] = {"a", "b", "c", "d"};
double d [][]= {
{0.50, 0.20, 0.20, 0.30},
{0.50, 1.10, 0.50, 0.80},
{0.50, 0.70, 0.40},
{0.50, 0.70},
{0.50},
};
System.out.println(Arrays.toString(s));
System.out.println(Arrays.deepToString(d));
}
}
Extend the size of an array
public class Main {
public static void main(String[] args) {
String[] names = new String[] { "A", "B", "C" };
String[] extended = new String[5];
extended[3] = "D";
extended[4] = "F";
System.arraycopy(names, 0, extended, 0, names.length);
for (String str : extended)
System.out.println(str);
}
}
/*
A
B
C
D
F
*/
Filling Elements in an Array
import java.util.Arrays;
public class Main {
public static void main(String[] argv) throws Exception {
boolean[] booleanArr = new boolean[10];
boolean booleanFillValue = false;
Arrays.fill(booleanArr, booleanFillValue);
}
}
//Filling Elements in an Array: byte type
import java.util.Arrays;
public class Main {
public static void main(String[] argv) throws Exception {
byte[] byteArr = new byte[10];
byte byteFillValue = (byte) 0xFF;
Arrays.fill(byteArr, byteFillValue);
}
}
//Filling Elements in an Array: char type
import java.util.Arrays;
public class Main {
public static void main(String[] argv) throws Exception {
char[] charArr = new char[10];
char charFillValue = "c";
Arrays.fill(charArr, charFillValue);
}
}
//Filling Elements in an Array: short type
import java.util.Arrays;
public class Main {
public static void main(String[] argv) throws Exception {
short[] shortArr = new short[10];
short shortFillValue = 2;
Arrays.fill(shortArr, shortFillValue);
}
}
//Filling Elements in an Array: int type
import java.util.Arrays;
public class Main {
public static void main(String[] argv) throws Exception {
int[] intArr = new int[10];
int intFillValue = -1;
Arrays.fill(intArr, intFillValue);
}
}
//Filling Elements in an Array: long type
import java.util.Arrays;
public class Main {
public static void main(String[] argv) throws Exception {
long[] longArr = new long[10];
long longFillValue = -1;
Arrays.fill(longArr, longFillValue);
}
}
//Filling Elements in an Array: float type
import java.util.Arrays;
public class Main {
public static void main(String[] argv) throws Exception {
float[] floatArr = new float[10];
float floatFillValue = -1;
Arrays.fill(floatArr, floatFillValue);
}
}
//Filling Elements in an Array: double type
import java.util.Arrays;
public class Main {
public static void main(String[] argv) throws Exception {
double[] doubleArr = new double[10];
double doubleFillValue = -1;
Arrays.fill(doubleArr, doubleFillValue);
}
}
filling object arrays:
import java.util.Arrays;
public class Main {
public static void main(String[] argv) throws Exception {
String[] StringArr = new String[1];
String StringFillValue = "";
Arrays.fill(StringArr, StringFillValue);
}
}
fill to a contiguous range of elements in an array
import java.util.Arrays;
public class Main {
public static void main(String[] argv) throws Exception {
int startIndex = 0;
int endIndex = 4;
boolean[] booleanArr = new boolean[10];
boolean booleanFillValue = true;
Arrays.fill(booleanArr, startIndex, endIndex, booleanFillValue);
}
}
//Fill to a contiguous range of elements in an array: byte array
import java.util.Arrays;
public class Main {
public static void main(String[] argv) throws Exception {
int startIndex = 0;
int endIndex = 4;
byte[] byteArr = new byte[10];
byte byteFillValue = 1;
Arrays.fill(byteArr, startIndex, endIndex, byteFillValue);
}
}
//Fill to a contiguous range of elements in an array: char array
import java.util.Arrays;
public class Main {
public static void main(String[] argv) throws Exception {
int startIndex = 0;
int endIndex = 4;
char[] charArr = new char[10];
char charFillValue = 1;
Arrays.fill(charArr, startIndex, endIndex, charFillValue);
}
}
//Fill to a contiguous range of elements in an array: short array
import java.util.Arrays;
public class Main {
public static void main(String[] argv) throws Exception {
int startIndex = 0;
int endIndex = 4;
short[] shortArr = new short[10];
short shortFillValue = 1;
Arrays.fill(shortArr, startIndex, endIndex, shortFillValue);
}
}
//Fill to a contiguous range of elements in an array: int array
import java.util.Arrays;
public class Main {
public static void main(String[] argv) throws Exception {
int startIndex = 0;
int endIndex = 4;
int[] intArr = new int[10];
int intFillValue = 1;
Arrays.fill(intArr, startIndex, endIndex, intFillValue);
}
}
//Fill to a contiguous range of elements in an array: long array
import java.util.Arrays;
public class Main {
public static void main(String[] argv) throws Exception {
int startIndex = 0;
int endIndex = 4;
long[] longArr = new long[10];
long longFillValue = 1;
Arrays.fill(longArr, startIndex, endIndex, longFillValue);
}
}
//Fill to a contiguous range of elements in an array: float array
import java.util.Arrays;
public class Main {
public static void main(String[] argv) throws Exception {
int startIndex = 0;
int endIndex = 4;
float[] floatArr = new float[10];
float floatFillValue = 1;
Arrays.fill(floatArr, startIndex, endIndex, floatFillValue);
}
}
//Fill to a contiguous range of elements in an array: double array
import java.util.Arrays;
public class Main {
public static void main(String[] argv) throws Exception {
int startIndex = 0;
int endIndex = 4;
double[] doubleArr = new double[10];
double doubleFillValue = 1;
Arrays.fill(doubleArr, startIndex, endIndex, doubleFillValue);
}
}
//Fill to a contiguous range of elements in an array: String array
import java.util.Arrays;
public class Main {
public static void main(String[] argv) throws Exception {
int startIndex = 0;
int endIndex = 4;
String[] stringArr = new String[10];
String stringFillValue = "1";
Arrays.fill(stringArr, startIndex, endIndex, stringFillValue);
}
}
Gets the subarray from array that starts at offset.
/*
* Copyright Aduna (http://www.aduna-software.ru/) (c) 1997-2006.
*
* Licensed under the Aduna BSD-style license.
*/
public class Utils {
/**
* Gets the subarray from <tt>array</tt> that starts at <tt>offset</tt>.
*/
public static byte[] get(byte[] array, int offset) {
return get(array, offset, array.length - offset);
}
/**
* Gets the subarray of length <tt>length</tt> from <tt>array</tt>
* that starts at <tt>offset</tt>.
*/
public static byte[] get(byte[] array, int offset, int length) {
byte[] result = new byte[length];
System.arraycopy(array, offset, result, 0, length);
return result;
}
}
Gets the subarray of length length from array that starts at offset.
/*
* Copyright Aduna (http://www.aduna-software.ru/) (c) 1997-2006.
*
* Licensed under the Aduna BSD-style license.
*/
public class Utils {
/**
* Gets the subarray of length <tt>length</tt> from <tt>array</tt>
* that starts at <tt>offset</tt>.
*/
public static byte[] get(byte[] array, int offset, int length) {
byte[] result = new byte[length];
System.arraycopy(array, offset, result, 0, length);
return result;
}
}
Growable String array with type specific access methods.
/*
Copyright (c) 2000-2008, Dennis M. Sosnoski.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of JiBX nor the names of its contributors may be used
to endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import java.lang.reflect.Array;
/**
* Growable <code>String</code> array with type specific access methods. This
* implementation is unsynchronized in order to provide the best possible
* performance for typical usage scenarios, so explicit synchronization must
* be implemented by a wrapper class or directly by the application in cases
* where instances are modified in a multithreaded environment.
*
* @author Dennis M. Sosnoski
*/
public class StringArray
{
/** Default initial array size. */
public static final int DEFAULT_SIZE = 8;
/** Size of the current array. */
private int m_countLimit;
/** The number of values currently present in the array. */
private int m_countPresent;
/** Maximum size increment for growing array. */
private int m_maximumGrowth;
/** The underlying array used for storing the data. */
private String[] m_baseArray;
/**
* Constructor with full specification.
*
* @param size number of <code>String</code> values initially allowed in
* array
* @param growth maximum size increment for growing array
*/
public StringArray(int size, int growth) {
String[] array = new String[size];
m_countLimit = size;
m_maximumGrowth = growth;
m_baseArray = array;
}
/**
* Constructor with initial size specified.
*
* @param size number of <code>String</code> values initially allowed in
* array
*/
public StringArray(int size) {
this(size, Integer.MAX_VALUE);
}
/**
* Default constructor.
*/
public StringArray() {
this(DEFAULT_SIZE);
}
/**
* Copy (clone) constructor.
*
* @param base instance being copied
*/
public StringArray(StringArray base) {
this(base.m_countLimit, base.m_maximumGrowth);
System.arraycopy(base.m_baseArray, 0, m_baseArray, 0,
base.m_countPresent);
m_countPresent = base.m_countPresent;
}
/**
* Copy data after array resize. This just copies the entire contents of the
* old array to the start of the new array. It should be overridden in cases
* where data needs to be rearranged in the array after a resize.
*
* @param base original array containing data
* @param grown resized array for data
*/
private void resizeCopy(Object base, Object grown) {
System.arraycopy(base, 0, grown, 0, Array.getLength(base));
}
/**
* Discards values for a range of indices in the array. Clears references to
* removed values.
*
* @param from index of first value to be discarded
* @param to index past last value to be discarded
*/
private void discardValues(int from, int to) {
for (int i = from; i < to; i++) {
m_baseArray[i] = null;
}
}
/**
* Increase the size of the array to at least a specified size. The array
* will normally be at least doubled in size, but if a maximum size
* increment was specified in the constructor and the value is less than
* the current size of the array, the maximum increment will be used
* instead. If the requested size requires more than the default growth,
* the requested size overrides the normal growth and determines the size
* of the replacement array.
*
* @param required new minimum size required
*/
private void growArray(int required) {
int size = Math.max(required,
m_countLimit + Math.min(m_countLimit, m_maximumGrowth));
String[] grown = new String[size];
resizeCopy(m_baseArray, grown);
m_countLimit = size;
m_baseArray = grown;
}
/**
* Ensure that the array has the capacity for at least the specified
* number of values.
*
* @param min minimum capacity to be guaranteed
*/
public final void ensureCapacity(int min) {
if (min > m_countLimit) {
growArray(min);
}
}
/**
* Overwrite an existing value in the array.
*
* @param index position of value to be overwritten
* @param value value to be added
*/
public void set(int index, String value) {
if (index < m_countPresent) {
m_baseArray[index] = value;
} else {
throw new IllegalArgumentException("Index value out of range");
}
}
/**
* Add a value at the end of the array.
*
* @param value value to be added
*/
public void add(String value) {
int index = getAddIndex();
m_baseArray[index] = value;
}
/**
* Add an array of values at the end of the array.
*
* @param values values to be added
*/
public void addAll(String[] values) {
ensureCapacity(m_countPresent+values.length);
for (int i = 0; i < values.length; i++) {
m_baseArray[m_countPresent++] = values[i];
}
}
/**
* Remove some number of values from the end of the array.
*
* @param count number of values to be removed
* @exception ArrayIndexOutOfBoundsException on attempt to remove more than
* the count present
*/
public void remove(int count) {
int start = m_countPresent - count;
if (start >= 0) {
discardValues(start, m_countPresent);
m_countPresent = start;
} else {
throw new ArrayIndexOutOfBoundsException
("Attempt to remove too many values from array");
}
}
/**
* Get a value from the array.
*
* @param index index of value to be returned
* @return value from stack
* @exception ArrayIndexOutOfBoundsException on attempt to access outside
* valid range
*/
public String get(int index) {
if (m_countPresent > index) {
return m_baseArray[index];
} else {
throw new ArrayIndexOutOfBoundsException
("Attempt to access past end of array");
}
}
/**
* Constructs and returns a simple array containing the same data as held
* in this array.
*
* @return array containing a copy of the data
*/
public String[] toArray() {
String[] copy = new String[m_countPresent];
System.arraycopy(m_baseArray, 0, copy, 0, m_countPresent);
return copy;
}
/**
* Duplicates the object with the generic call.
*
* @return a copy of the object
*/
public Object clone() {
return new StringArray(this);
}
/**
* Gets the array offset for appending a value to those in the array. If the
* underlying array is full, it is grown by the appropriate size increment
* so that the index value returned is always valid for the array in use by
* the time of the return.
*
* @return index position for added element
*/
private int getAddIndex() {
int index = m_countPresent++;
if (m_countPresent > m_countLimit) {
growArray(m_countPresent);
}
return index;
}
/**
* Get the number of values currently present in the array.
*
* @return count of values present
*/
public int size() {
return m_countPresent;
}
/**
* Check if array is empty.
*
* @return <code>true</code> if array empty, <code>false</code> if not
*/
public boolean isEmpty() {
return m_countPresent == 0;
}
/**
* Set the array to the empty state.
*/
public void clear() {
discardValues(0, m_countPresent);
m_countPresent = 0;
}
}
How to copy an array
public class Main {
public static void main(String[] args) {
int[] intArray = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
int[] arrayCopy = new int[intArray.length];
System.arraycopy(intArray, 0, arrayCopy, 0, intArray.length);
for (int i = 0; i < arrayCopy.length; i++)
System.out.println(arrayCopy[i]);
}
}
/*
1
2
3
4
5
6
7
8
9
0
*/
How to sort an array
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] intArray = new int[] { 4, 5, 9, 0, 3, 5, 6, 2 };
Arrays.sort(intArray);
for (int i = 0; i < intArray.length; i++)
System.out.println(intArray[i]);
String[] stringArray = new String[] { "D", "E", "A", "C", "B" };
Arrays.sort(stringArray);
for (int i = 0; i < stringArray.length; i++)
System.out.println(stringArray[i]);
}
}
/*0
2
3
4
5
5
6
9
A
B
C
D
E
*/
If the given objects are equal
import java.lang.reflect.Array;
import java.util.Arrays;
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//Revised from springframework
/**
* Miscellaneous object utility methods. Mainly for internal use within the
* framework; consider Jakarta"s Commons Lang for a more comprehensive suite
* of object utilities.
*
* @author Juergen Hoeller
* @author Keith Donald
* @author Rod Johnson
* @author Rob Harrop
* @author Alex Ruiz
* @since 19.03.2004
* @see org.apache.rumons.lang.ObjectUtils
*/
abstract class ObjectUtils {
private static final int INITIAL_HASH = 7;
private static final int MULTIPLIER = 31;
private static final String EMPTY_STRING = "";
private static final String NULL_STRING = "null";
private static final String ARRAY_START = "{";
private static final String ARRAY_END = "}";
private static final String EMPTY_ARRAY = ARRAY_START + ARRAY_END;
private static final String ARRAY_ELEMENT_SEPARATOR = ", ";
/**
* Determine if the given objects are equal, returning <code>true</code>
* if both are <code>null</code> or <code>false</code> if only one is
* <code>null</code>.
* Compares arrays with <code>Arrays.equals</code>, performing an equality
* check based on the array elements rather than the array reference.
* @param o1 first Object to compare
* @param o2 second Object to compare
* @return whether the given objects are equal
* @see java.util.Arrays#equals
*/
public static boolean nullSafeEquals(Object o1, Object o2) {
if (o1 == o2) {
return true;
}
if (o1 == null || o2 == null) {
return false;
}
if (o1.equals(o2)) {
return true;
}
if (o1 instanceof Object[] && o2 instanceof Object[]) {
return Arrays.equals((Object[]) o1, (Object[]) o2);
}
if (o1 instanceof boolean[] && o2 instanceof boolean[]) {
return Arrays.equals((boolean[]) o1, (boolean[]) o2);
}
if (o1 instanceof byte[] && o2 instanceof byte[]) {
return Arrays.equals((byte[]) o1, (byte[]) o2);
}
if (o1 instanceof char[] && o2 instanceof char[]) {
return Arrays.equals((char[]) o1, (char[]) o2);
}
if (o1 instanceof double[] && o2 instanceof double[]) {
return Arrays.equals((double[]) o1, (double[]) o2);
}
if (o1 instanceof float[] && o2 instanceof float[]) {
return Arrays.equals((float[]) o1, (float[]) o2);
}
if (o1 instanceof int[] && o2 instanceof int[]) {
return Arrays.equals((int[]) o1, (int[]) o2);
}
if (o1 instanceof long[] && o2 instanceof long[]) {
return Arrays.equals((long[]) o1, (long[]) o2);
}
if (o1 instanceof short[] && o2 instanceof short[]) {
return Arrays.equals((short[]) o1, (short[]) o2);
}
return false;
}
}
Java Sort byte Array
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
byte[] b1 = new byte[] { 3, 2, 5, 4, 1 };
for (byte b: b1){
System.out.println(b);
}
Arrays.sort(b1);
for (byte b: b1){
System.out.println(b);
}
byte[] b2 = new byte[] { 5, 2, 3, 1, 4 };
Arrays.sort(b2, 1, 4);
for (byte b: b2){
System.out.println(b);
}
}
}
Java Sort char Array
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
char[] c1 = new char[] { "c", "h", "a", "r", "s" };
for (char ch: c1){
System.out.print(ch);
}
Arrays.sort(c1);
for (char ch: c1){
System.out.print(ch);
}
char[] c2 = new char[] { "c", "h", "a", "r", "s" };
Arrays.sort(c2, 1, 4);
for (char ch: c1){
System.out.print(ch);
}
}
}
Java Sort double Array
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
double[] d1 = new double[] { 3.1, 2.1, 5.1, 4.1, 1.1 };
for (double d: d1){
System.out.print(" " +d);
}
Arrays.sort(d1);
for (double d: d1){
System.out.print(" " +d);
}
double[] d2 = new double[] { 5, 2, 3, 1, 4 };
Arrays.sort(d2, 1, 4);
for (double d: d2){
System.out.print(" " +d);
}
}
}
Java Sort float Array
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
float[] f1 = new float[] { 3.1f, 2.1f, 5.1f, 4.1f, 1.1f };
for (float f: f1){
System.out.print(" " + f);
}
Arrays.sort(f1);
for (float f: f1){
System.out.print(" " + f);
}
float[] f2 = new float[] { 5.1f, 2.1f, 3.1f, 1.1f, 4.1f };
Arrays.sort(f2, 1, 4);
for (float f: f2){
System.out.print(" " + f);
}
}
}
java.utils.Arrays provides ways to dump the content of an array.
import java.util.Arrays;
public class Main {
public static void main(String args[]) {
String s[] = {"a", "b", "c", "d"};
double d [][]= {
{0.50, 0.20, 0.20, 0.30},
{0.50, 1.10, 0.50, 0.80},
{0.50, 0.70, 0.40},
{0.50, 0.70},
{0.50},
};
System.out.println(Arrays.toString(s));
System.out.println(Arrays.deepToString(d));
}
}
Minimum and maximum number in array
import java.util.Arrays;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
Integer[] numbers = { 8, 2, 6, 7, 0, 1, 4, 9, 5, 3 };
int min = (int) Collections.min(Arrays.asList(numbers));
int max = (int) Collections.max(Arrays.asList(numbers));
System.out.println("Min number: " + min);
System.out.println("Max number: " + max);
}
}
Performing Binary Search on Java Array
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
byte bArray[] = { 1, 2, 4, 5 };
Arrays.sort(bArray);
byte searchValue = 2;
int intResult = Arrays.binarySearch(bArray, searchValue);
System.out.println("Result of binary search of 2 is : " + intResult);
searchValue = 7;
intResult = Arrays.binarySearch(bArray, searchValue);
System.out.println("Result of binary search of 3 is : " + intResult);
}
}
//Performing Binary Search on Java char Array
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
char charArray[] = { "a", "b", "d", "e" };
Arrays.sort(charArray);
char searchValue = "b";
System.out.println(Arrays.binarySearch(charArray, searchValue));
searchValue = "z";
System.out.println(Arrays.binarySearch(charArray, searchValue));
}
}
//Performing Binary Search on Java double Array
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
double doubleArray[] = { 1.3, 2.1, 4.7, 5.3 };
Arrays.sort(doubleArray);
double searchValue = 4.7;
System.out.println(Arrays.binarySearch(doubleArray, searchValue));
searchValue = 3.33;
System.out.println(Arrays.binarySearch(doubleArray, searchValue));
}
}
//Performing Binary Search on Java float Array Example
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
float floatArray[] = { 1.2f, 2.1f, 4.7f, 5.3f };
Arrays.sort(floatArray);
float searchValue = 4.7f;
System.out.println(Arrays.binarySearch(floatArray, searchValue));
searchValue = 3.3f;
System.out.println(Arrays.binarySearch(floatArray, searchValue));
}
}
//Performing Binary Search on Java int Array
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int intArray[] = { 1, 2, 4, 5 };
Arrays.sort(intArray);
int searchValue = 2;
System.out.println(Arrays.binarySearch(intArray, searchValue));
searchValue = 3;
System.out.println(Arrays.binarySearch(intArray, searchValue));
}
}
//Performing Binary Search on Java long Array
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
long longArray[] = { 1L, 2L, 4L, 5L };
Arrays.sort(longArray);
long searchValue = 2L;
System.out.println(Arrays.binarySearch(longArray, searchValue));
searchValue = 3;
System.out.println(Arrays.binarySearch(longArray, searchValue));
}
}
//Performing Binary Search on Java short Array
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
short shortArray[] = { 1, 2, 4, 5 };
Arrays.sort(shortArray);
short searchValue = 2;
System.out.println(Arrays.binarySearch(shortArray, searchValue));
searchValue = 3;
System.out.println(Arrays.binarySearch(shortArray, searchValue));
}
}
Reverses the order of the given object array.
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
public class Main {
/**
* Reverses the order of the given array.</p>
*
* There is no special handling for multi-dimensional arrays.</p>
*
* This method does nothing for a <code>null</code> input array.</p>
*
* @param array the array to reverse, may be <code>null</code>
*/
public static void reverse(Object[] array) {
if (array == null) {
return;
}
int i = 0;
int j = array.length - 1;
Object tmp;
while (j > i) {
tmp = array[j];
array[j] = array[i];
array[i] = tmp;
j--;
i++;
}
}
}
Shifting Elements in an Array: Shift all elements left by one
public class Main {
public static void main(String[] argv) throws Exception {
int[] array = { 1, 2, 3 };
System.arraycopy(array, 1, array, 0, array.length - 1);
}
}
Shifting Elements in an Array: Shift all elements right by one
import java.util.Arrays;
public class Main {
public static void main(String[] argv) throws Exception {
int[] array = { 1, 2, 3 };
System.arraycopy(array, 0, array, 1, array.length - 1);
System.out.println(Arrays.toString(array));
}
}
//[1, 1, 2]
Shuffle elements of an array
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Main {
public static void main(String[] args) {
String[] alphabets = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J" };
List<String> list = Arrays.asList(alphabets);
Collections.shuffle(list);
for (String alpha : list) {
System.out.print(alpha + " ");
}
}
}
Sort an array: case-insensitive
import java.text.Collator;
import java.util.Arrays;
public class Main {
public static void main(String args[]) {
String[] myArray = new String[] { "A", "B", "b" };
Arrays.sort(myArray, Collator.getInstance());
System.out.println(Arrays.toString(myArray));
}
}
//[A, b, B]
Sort an array: case-sensitive
import java.util.Arrays;
public class Main {
public static void main(String args[]) {
String[] myArray = new String[] { "A", "a", "B" };
Arrays.sort(myArray);
System.out.println(Arrays.toString(myArray));
}
}
//[A, B, a]
Sorting an Array in Descending (Reverse) Order
import java.util.Arrays;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
Integer[] arrayToSort = new Integer[] {
new Integer(5),
new Integer(89),
new Integer(16),
new Integer(2)
};
Arrays.sort(arrayToSort, Collections.reverseOrder());
for (Integer i : arrayToSort) {
System.out.println(i.intValue());
}
}
}
/*89
16
5
2
*/
Use java.util.Arrays.deepToString() to dump the multi-dimensional arrays
import java.util.Arrays;
public class Main {
public static void main(String args[]) {
String s[] = {"a", "b", "c", "d"};
double d [][]= {
{0.50, 0.20, 0.20, 0.30},
{0.50, 1.10, 0.50, 0.80},
{0.50, 0.70, 0.40},
{0.50, 0.70},
{0.50},
};
System.out.println(Arrays.toString(s));
System.out.println(Arrays.deepToString(d));
}
}
Wrapper for arrays of ordered strings. This verifies the arrays and supports efficient lookups.
/**
* Wrapper for arrays of ordered strings. This verifies the arrays and supports
* efficient lookups.
*
* @author Dennis M. Sosnoski
*/
public class StringArray
{
/** Ordered array of strings. */
private final String[] m_list;
/**
* Constructor from array of values. This checks the array values to make
* sure they"re ordered and unique, and if they"re not throws an exception.
* Once the array has been passed to this constructor it must not be
* modified by outside code.
*
* @param list array of values
*/
public StringArray(String[] list) {
validateArray(list);
m_list = list;
}
/**
* Constructor from array of values to be added to base instance. This
* merges the array values, making sure they"re ordered and unique, and if
* they"re not throws an exception.
*
* @param list array of values
* @param base base instance
*/
public StringArray(String[] list, StringArray base) {
validateArray(list);
m_list = mergeArrays(list, base.m_list);
}
/**
* Constructor from pair of base instances. This merges the values, making
* sure they"re unique, and if they"re not throws an exception.
*
* @param array1 first base array
* @param array2 second base array
*/
public StringArray(StringArray array1, StringArray array2) {
m_list = mergeArrays(array1.m_list, array2.m_list);
}
/**
* Constructor from array of values to be added to pair of base instances.
* This merges the array values, making sure they"re ordered and unique, and
* if they"re not throws an exception.
*
* @param list array of values
* @param array1 first base array
* @param array2 second base array
*/
public StringArray(String[] list, StringArray array1, StringArray array2) {
validateArray(list);
m_list = mergeArrays(list, mergeArrays(array1.m_list, array2.m_list));
}
/**
* Constructor from array of values to be added to three base instances.
* This merges the array values, making sure they"re ordered and unique, and
* if they"re not throws an exception.
*
* @param list array of values
* @param array1 first base array
* @param array2 second base array
* @param array3 third base array
*/
public StringArray(String[] list, StringArray array1, StringArray array2,
StringArray array3) {
validateArray(list);
m_list = mergeArrays(list, mergeArrays(array1.m_list,
mergeArrays(array2.m_list, array3.m_list)));
}
/**
* Constructor from array of values to be added to four base instances.
* This merges the array values, making sure they"re ordered and unique, and
* if they"re not throws an exception.
*
* @param list array of values
* @param array1 first base array
* @param array2 second base array
* @param array3 third base array
* @param array4 fourth base array
*/
public StringArray(String[] list, StringArray array1, StringArray array2,
StringArray array3, StringArray array4) {
validateArray(list);
m_list = mergeArrays(list, mergeArrays(array1.m_list,
mergeArrays(array2.m_list,
mergeArrays(array3.m_list, array4.m_list))));
}
/**
* Merge a pair of ordered arrays into a single array. The two source arrays
* must not contain any values in common.
*
* @param list1 first ordered array
* @param list2 second ordered array
* @return merged array
*/
private String[] mergeArrays(String[] list1, String[] list2) {
String[] merge = new String[list1.length + list2.length];
int fill = 0;
int i = 0;
int j = 0;
while (i < list1.length && j < list2.length) {
int diff = list2[j].rupareTo(list1[i]);
if (diff > 0) {
merge[fill++] = list1[i++];
} else if (diff < 0) {
merge[fill++] = list2[j++];
} else {
throw new IllegalArgumentException
("Repeated value not allowed: \"" + list1[i] + """);
}
}
if (i < list1.length) {
System.arraycopy(list1, i, merge, fill, list1.length-i);
}
if (j < list2.length) {
System.arraycopy(list2, j, merge, fill, list2.length-j);
}
return merge;
}
/**
* Make sure passed-in array contains values that are in order and without
* duplicate values.
*
* @param list
*/
private void validateArray(String[] list) {
if (list.length > 0) {
String last = list[0];
int index = 0;
while (++index < list.length) {
String comp = list[index];
int diff = last.rupareTo(comp);
if (diff > 0) {
throw new IllegalArgumentException
("Array values are not ordered");
} else if (diff < 0) {
last = comp;
} else {
throw new IllegalArgumentException
("Duplicate values in array");
}
}
}
}
/**
* Get string at a particular index in the list.
*
* @param index list index to be returned
* @return string at that index position
*/
public String get(int index) {
return m_list[index];
}
/**
* Find index of a particular string in the array. This does
* a binary search through the array values, using a pair of
* index bounds to track the subarray of possible matches at
* each iteration.
*
* @param value string to be found in list
* @return index of string in array, or <code>-1</code> if
* not present
*/
public int indexOf(String value) {
int base = 0;
int limit = m_list.length - 1;
while (base <= limit) {
int cur = (base + limit) >> 1;
int diff = value.rupareTo(m_list[cur]);
if (diff < 0) {
limit = cur - 1;
} else if (diff > 0) {
base = cur + 1;
} else {
return cur;
}
}
return -1;
}
/**
* Get number of values in array
*
* @return number of values in array
*/
public int size() {
return m_list.length;
}
}