Java/Collections Data Structure/Array Sort Search — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Текущая версия на 07:24, 1 июня 2010
Содержание
- 1 Check if object 1 contains object 2
- 2 Find items in an array
- 3 Finds the index of the given object in the array.
- 4 Finds the index of the given object in the array starting at the given index.
- 5 Finds the last index of the given object in the array starting at the given index.
- 6 Finds the last index of the given object within the array.
- 7 Get index of long type array
- 8 Get the element index and last index in a float type value array
- 9 Get the element index or last index among a boolean type array
- 10 Get the index and last index of a char type value array
- 11 Get the index and last index of a double type array
- 12 Get the index and last index of an int type value array
- 13 Get the index and last index of a short type value array
- 14 Get the index and last index of byte type array
- 15 How to sort an array
- 16 If array contains given element
- 17 Inserting an Element into a Sorted Array
- 18 Produces a new array containing the elements between the start and end indices.
- 19 Produces a new boolean array containing the elements between the start and end indices.
- 20 Produces a new byte array containing the elements between the start and end indices.
- 21 Produces a new char array containing the elements between the start and end indices.
- 22 Produces a new double array containing the elements between the start and end indices.
- 23 Produces a new float array containing the elements between the start and end indices.
- 24 Produces a new int array containing the elements between the start and end indices.
- 25 Produces a new long array containing the elements between the start and end indices.
- 26 Produces a new short array containing the elements between the start and end indices.
- 27 Quicksort implementation for sorting arrays
- 28 Returns the index in the source array where the first occurrence of the specified byte pattern is found
- 29 Returns the index in the source array where the first occurrence of the specified text (a String, converted to a byte array) is found
- 30 Returns the index in the source array where the last occurrence of the specified byte pattern is found
- 31 Returns the index in the source array where the last occurrence of the specified text (a String, converted to a byte array) is found
- 32 Returns the maximum value in a byte-type array.
- 33 Returns the maximum value in a double-type array.
- 34 Returns the maximum value in a float-type array.
- 35 Returns the maximum value in a long-value array.
- 36 Returns the maximum value in an int-type array.
- 37 Returns the maximum value in a short-type array.
- 38 Returns the minimum value in a double-type array.
- 39 Returns the minimum value in a float-value array.
- 40 Returns the minimum value in an array.
- 41 Returns the minimum value in an int-type array.
- 42 Returns the minimum value in an short-type array.
- 43 Returns the minimum value in a short-type array.
- 44 Reverses the order of the given boolean type value array.
- 45 Reverses the order of the given byte type array.
- 46 Reverses the order of the given char type value array.
- 47 Reverses the order of the given double value type array.
- 48 Reverses the order of the given float type value array.
- 49 Reverses the order of the given int type value array.
- 50 Reverses the order of the given long type value array.
- 51 Reverses the order of the given object array.
- 52 Reverses the order of the given short type value array.
- 53 Search for an object in an array.
- 54 Search for a specified value of an array
- 55 Sort array utilities
- 56 Sort array values in descending order
- 57 Sorting an Array
- 58 Sorting an Array in Descending (Reverse) Order
- 59 Sort in reverse order
Check if object 1 contains object 2
/*
* Copyright (c) 2002-2003 by OpenSymphony
* All rights reserved.
*/
import java.lang.reflect.Array;
import java.util.Collection;
import java.util.Map;
/**
* <code>ContainUtil</code> will check if object 1 contains object 2.
* Object 1 may be an Object, array, Collection, or a Map
*
* @author Matt Baldree (matt@smallleap.ru)
* @version $Revision: 2737 $
*/
public class ContainUtil {
/**
* Determine if <code>obj2</code> exists in <code>obj1</code>.
*
* <table borer="1">
* <tr>
* <td>Type Of obj1</td>
* <td>Comparison type</td>
* </tr>
* <tr>
* <td>null<td>
* <td>always return false</td>
* </tr>
* <tr>
* <td>Map</td>
* <td>Map containsKey(obj2)</td>
* </tr>
* <tr>
* <td>Collection</td>
* <td>Collection contains(obj2)</td>
* </tr>
* <tr>
* <td>Array</td>
* <td>there"s an array element (e) where e.equals(obj2)</td>
* </tr>
* <tr>
* <td>Object</td>
* <td>obj1.equals(obj2)</td>
* </tr>
* </table>
*
*
* @param obj1
* @param obj2
* @return
*/
public static boolean contains(Object obj1, Object obj2) {
if ((obj1 == null) || (obj2 == null)) {
//log.debug("obj1 or obj2 are null.");
return false;
}
if (obj1 instanceof Map) {
if (((Map) obj1).containsKey(obj2)) {
//log.debug("obj1 is a map and contains obj2");
return true;
}
} else if (obj1 instanceof Collection) {
if (((Collection) obj1).contains(obj2)) {
//log.debug("obj1 is a collection and contains obj2");
return true;
}
} else if (obj1.getClass().isArray()) {
for (int i = 0; i < Array.getLength(obj1); i++) {
Object value = null;
value = Array.get(obj1, i);
if (value.equals(obj2)) {
//log.debug("obj1 is an array and contains obj2");
return true;
}
}
} else if (obj1.equals(obj2)) {
//log.debug("obj1 is an object and equals obj2");
return true;
}
//log.debug("obj1 does not contain obj2: " + obj1 + ", " + obj2);
return false;
}
}
////////////////
package com.opensymphony.webwork.util;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import junit.framework.TestCase;
import com.opensymphony.webwork.util.ContainUtil;
public class ContainUtilTest extends TestCase {
public void testNull() throws Exception {
assertFalse(ContainUtil.contains(null, null));
assertFalse(ContainUtil.contains(new Object(), null));
assertFalse(ContainUtil.contains(null, new Object()));
}
public void testSimpleList() throws Exception {
List l = new ArrayList();
l.add("one");
l.add("two");
assertFalse(ContainUtil.contains(l, "three"));
assertTrue(ContainUtil.contains(l, "one"));
assertTrue(ContainUtil.contains(l, "two"));
}
public void testSimpleSet() throws Exception {
Set s = new LinkedHashSet();
s.add("one");
s.add("two");
assertFalse(ContainUtil.contains(s, "thre"));
assertTrue(ContainUtil.contains(s, "one"));
assertTrue(ContainUtil.contains(s, "two"));
}
public void testComplexList() throws Exception {
List l = new ArrayList();
l.add(new MyObject("tm_jee", Integer.valueOf("20")));
l.add(new MyObject("jenny", Integer.valueOf("22")));
assertFalse(ContainUtil.contains(l, new MyObject("paul", Integer.valueOf("50"))));
assertFalse(ContainUtil.contains(l, new MyObject("tm_jee", Integer.valueOf("44"))));
assertTrue(ContainUtil.contains(l, new MyObject("tm_jee", Integer.valueOf("20"))));
assertTrue(ContainUtil.contains(l, new MyObject("jenny", Integer.valueOf("22"))));
}
public void testComplexMap() throws Exception {
Set s = new LinkedHashSet();
s.add(new MyObject("tm_jee", Integer.valueOf("20")));
s.add(new MyObject("jenny", Integer.valueOf("22")));
assertFalse(ContainUtil.contains(s, new MyObject("paul", Integer.valueOf("50"))));
assertFalse(ContainUtil.contains(s, new MyObject("tm_jee", Integer.valueOf("44"))));
assertTrue(ContainUtil.contains(s, new MyObject("tm_jee", Integer.valueOf("20"))));
assertTrue(ContainUtil.contains(s, new MyObject("jenny", Integer.valueOf("22"))));
}
public void testObject() throws Exception {
assertFalse(ContainUtil.contains("aaa", "bbb"));
assertFalse(ContainUtil.contains(new MyObject("tm_jee", Integer.valueOf("22")), new MyObject("tmjee", Integer.valueOf("22"))));
assertTrue(ContainUtil.contains("apple", "apple"));
assertTrue(ContainUtil.contains(new MyObject("tm_jee", Integer.valueOf("22")), new MyObject("tm_jee", Integer.valueOf("22"))));
}
public static class MyObject {
private String name;
private Integer age;
public MyObject(String name, Integer age) {
this.name = name;
this.age = age;
}
public int hashCode() {
return this.name.hashCode();
}
public boolean equals(Object obj) {
if (obj == null) { return false; }
if (! (obj instanceof MyObject)) { return false; }
MyObject tmp = (MyObject) obj;
if (
tmp.name.equals(this.name) &&
tmp.age.equals(this.age)
) {
return true;
}
return false;
}
}
}
Find items in an array
import org.apache.rumons.lang.ArrayUtils;
public class Main {
public static void main(String[] args) {
String[] colours = { "Red", "Orange", "Yellow", "Green", "Blue", "Violet", "Orange", "Blue" };
boolean contains = ArrayUtils.contains(colours, "Blue");
System.out.println("Contains Blue? " + contains);
int indexOfYellow = ArrayUtils.indexOf(colours, "Yellow");
System.out.println("indexOfYellow = " + indexOfYellow);
int indexOfOrange = ArrayUtils.indexOf(colours, "Orange");
System.out.println("indexOfOrange = " + indexOfOrange);
int lastIndexOfOrange = ArrayUtils.lastIndexOf(colours, "Orange");
System.out.println("lastIndexOfOrange = " + lastIndexOfOrange);
}
}
Finds the index of the given object in the array.
/* Copyright 2004 The Apache Software Foundation
*
* 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.
*/
import java.lang.reflect.Array;
/**
* <p>Operations on arrays, primitive arrays (like <code>int[]</code>) and
* primitive wrapper arrays (like <code>Integer[]</code>).</p>
*
* <p>This class tries to handle <code>null</code> input gracefully.
* An exception will not be thrown for a <code>null</code>
* array input. However, an Object array that contains a <code>null</code>
* element may throw an exception. Each method documents its behaviour.</p>
*
* @author Stephen Colebourne
* @author Moritz Petersen
* @author
* @author Maarten Coene
* @since 2.0
* @version $Id: ArrayUtils.java 632503 2008-03-01 00:21:52Z ggregory $
*/
public class Main {
/**
* <p>Finds the index of the given object in the array.</p>
*
* <p>This method returns {@link #INDEX_NOT_FOUND} (<code>-1</code>) for a <code>null</code> input array.</p>
*
* @param array the array to search through for the object, may be <code>null</code>
* @param objectToFind the object to find, may be <code>null</code>
* @return the index of the object within the array,
* {@link #INDEX_NOT_FOUND} (<code>-1</code>) if not found or <code>null</code> array input
*/
public static int indexOf(Object[] array, Object objectToFind) {
return indexOf(array, objectToFind, 0);
}
/**
* <p>Finds the index of the given object in the array starting at the given index.</p>
*
* <p>This method returns {@link #INDEX_NOT_FOUND} (<code>-1</code>) for a <code>null</code> input array.</p>
*
* <p>A negative startIndex is treated as zero. A startIndex larger than the array
* length will return {@link #INDEX_NOT_FOUND} (<code>-1</code>).</p>
*
* @param array the array to search through for the object, may be <code>null</code>
* @param objectToFind the object to find, may be <code>null</code>
* @param startIndex the index to start searching at
* @return the index of the object within the array starting at the index,
* {@link #INDEX_NOT_FOUND} (<code>-1</code>) if not found or <code>null</code> array input
*/
public static int indexOf(Object[] array, Object objectToFind, int startIndex) {
if (array == null) {
return -1;
}
if (startIndex < 0) {
startIndex = 0;
}
if (objectToFind == null) {
for (int i = startIndex; i < array.length; i++) {
if (array[i] == null) {
return i;
}
}
} else {
for (int i = startIndex; i < array.length; i++) {
if (objectToFind.equals(array[i])) {
return i;
}
}
}
return -1;
}
}
Finds the index of the given object in the array starting at the given index.
/* Copyright 2004 The Apache Software Foundation
*
* 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.
*/
import java.lang.reflect.Array;
/**
* <p>Operations on arrays, primitive arrays (like <code>int[]</code>) and
* primitive wrapper arrays (like <code>Integer[]</code>).</p>
*
* <p>This class tries to handle <code>null</code> input gracefully.
* An exception will not be thrown for a <code>null</code>
* array input. However, an Object array that contains a <code>null</code>
* element may throw an exception. Each method documents its behaviour.</p>
*
* @author Stephen Colebourne
* @author Moritz Petersen
* @author
* @author Maarten Coene
* @since 2.0
* @version $Id: ArrayUtils.java 632503 2008-03-01 00:21:52Z ggregory $
*/
public class Main {
/**
* <p>Finds the index of the given object in the array starting at the given index.</p>
*
* <p>This method returns {@link #INDEX_NOT_FOUND} (<code>-1</code>) for a <code>null</code> input array.</p>
*
* <p>A negative startIndex is treated as zero. A startIndex larger than the array
* length will return {@link #INDEX_NOT_FOUND} (<code>-1</code>).</p>
*
* @param array the array to search through for the object, may be <code>null</code>
* @param objectToFind the object to find, may be <code>null</code>
* @param startIndex the index to start searching at
* @return the index of the object within the array starting at the index,
* {@link #INDEX_NOT_FOUND} (<code>-1</code>) if not found or <code>null</code> array input
*/
public static int indexOf(Object[] array, Object objectToFind, int startIndex) {
if (array == null) {
return -1;
}
if (startIndex < 0) {
startIndex = 0;
}
if (objectToFind == null) {
for (int i = startIndex; i < array.length; i++) {
if (array[i] == null) {
return i;
}
}
} else {
for (int i = startIndex; i < array.length; i++) {
if (objectToFind.equals(array[i])) {
return i;
}
}
}
return -1;
}
}
Finds the last index of the given object in the array starting at the given index.
/* Copyright 2004 The Apache Software Foundation
*
* 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.
*/
import java.lang.reflect.Array;
/**
* <p>Operations on arrays, primitive arrays (like <code>int[]</code>) and
* primitive wrapper arrays (like <code>Integer[]</code>).</p>
*
* <p>This class tries to handle <code>null</code> input gracefully.
* An exception will not be thrown for a <code>null</code>
* array input. However, an Object array that contains a <code>null</code>
* element may throw an exception. Each method documents its behaviour.</p>
*
* @author Stephen Colebourne
* @author Moritz Petersen
* @author
* @author Maarten Coene
* @since 2.0
* @version $Id: ArrayUtils.java 632503 2008-03-01 00:21:52Z ggregory $
*/
public class Main {
/**
* <p>Finds the last index of the given object in the array starting at the given index.</p>
*
* <p>This method returns {@link #INDEX_NOT_FOUND} (<code>-1</code>) for a <code>null</code> input array.</p>
*
* <p>A negative startIndex will return {@link #INDEX_NOT_FOUND} (<code>-1</code>). A startIndex larger than
* the array length will search from the end of the array.</p>
*
* @param array the array to traverse for looking for the object, may be <code>null</code>
* @param objectToFind the object to find, may be <code>null</code>
* @param startIndex the start index to travers backwards from
* @return the last index of the object within the array,
* {@link #INDEX_NOT_FOUND} (<code>-1</code>) if not found or <code>null</code> array input
*/
public static int lastIndexOf(Object[] array, Object objectToFind, int startIndex) {
if (array == null) {
return -1;
}
if (startIndex < 0) {
return -1;
} else if (startIndex >= array.length) {
startIndex = array.length - 1;
}
if (objectToFind == null) {
for (int i = startIndex; i >= 0; i--) {
if (array[i] == null) {
return i;
}
}
} else {
for (int i = startIndex; i >= 0; i--) {
if (objectToFind.equals(array[i])) {
return i;
}
}
}
return -1;
}
}
Finds the last index of the given object within the array.
/* Copyright 2004 The Apache Software Foundation
*
* 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.
*/
import java.lang.reflect.Array;
/**
* <p>Operations on arrays, primitive arrays (like <code>int[]</code>) and
* primitive wrapper arrays (like <code>Integer[]</code>).</p>
*
* <p>This class tries to handle <code>null</code> input gracefully.
* An exception will not be thrown for a <code>null</code>
* array input. However, an Object array that contains a <code>null</code>
* element may throw an exception. Each method documents its behaviour.</p>
*
* @author Stephen Colebourne
* @author Moritz Petersen
* @author
* @author Maarten Coene
* @since 2.0
* @version $Id: ArrayUtils.java 632503 2008-03-01 00:21:52Z ggregory $
*/
public class Main {
/**
* <p>Finds the last index of the given object within the array.</p>
*
* <p>This method returns {@link #INDEX_NOT_FOUND} (<code>-1</code>) for a <code>null</code> input array.</p>
*
* @param array the array to travers backwords looking for the object, may be <code>null</code>
* @param objectToFind the object to find, may be <code>null</code>
* @return the last index of the object within the array,
* {@link #INDEX_NOT_FOUND} (<code>-1</code>) if not found or <code>null</code> array input
*/
public static int lastIndexOf(Object[] array, Object objectToFind) {
return lastIndexOf(array, objectToFind, Integer.MAX_VALUE);
}
/**
* <p>Finds the last index of the given object in the array starting at the given index.</p>
*
* <p>This method returns {@link #INDEX_NOT_FOUND} (<code>-1</code>) for a <code>null</code> input array.</p>
*
* <p>A negative startIndex will return {@link #INDEX_NOT_FOUND} (<code>-1</code>). A startIndex larger than
* the array length will search from the end of the array.</p>
*
* @param array the array to traverse for looking for the object, may be <code>null</code>
* @param objectToFind the object to find, may be <code>null</code>
* @param startIndex the start index to travers backwards from
* @return the last index of the object within the array,
* {@link #INDEX_NOT_FOUND} (<code>-1</code>) if not found or <code>null</code> array input
*/
public static int lastIndexOf(Object[] array, Object objectToFind, int startIndex) {
if (array == null) {
return -1;
}
if (startIndex < 0) {
return -1;
} else if (startIndex >= array.length) {
startIndex = array.length - 1;
}
if (objectToFind == null) {
for (int i = startIndex; i >= 0; i--) {
if (array[i] == null) {
return i;
}
}
} else {
for (int i = startIndex; i >= 0; i--) {
if (objectToFind.equals(array[i])) {
return i;
}
}
}
return -1;
}
}
Get index of long type array
/* Copyright 2004 The Apache Software Foundation
*
* 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.
*/
import java.lang.reflect.Array;
/**
* <p>Operations on arrays, primitive arrays (like <code>int[]</code>) and
* primitive wrapper arrays (like <code>Integer[]</code>).</p>
*
* <p>This class tries to handle <code>null</code> input gracefully.
* An exception will not be thrown for a <code>null</code>
* array input. However, an Object array that contains a <code>null</code>
* element may throw an exception. Each method documents its behaviour.</p>
*
* @author Stephen Colebourne
* @author Moritz Petersen
* @author
* @author Maarten Coene
* @since 2.0
* @version $Id: ArrayUtils.java 632503 2008-03-01 00:21:52Z ggregory $
*/
public class Main {
// long IndexOf
//-----------------------------------------------------------------------
/**
* <p>Finds the index of the given value in the array.</p>
*
* <p>This method returns {@link #INDEX_NOT_FOUND} (<code>-1</code>) for a <code>null</code> input array.</p>
*
* @param array the array to search through for the object, may be <code>null</code>
* @param valueToFind the value to find
* @return the index of the value within the array,
* {@link #INDEX_NOT_FOUND} (<code>-1</code>) if not found or <code>null</code> array input
*/
public static int indexOf(long[] array, long valueToFind) {
return indexOf(array, valueToFind, 0);
}
/**
* <p>Finds the index of the given value in the array starting at the given index.</p>
*
* <p>This method returns {@link #INDEX_NOT_FOUND} (<code>-1</code>) for a <code>null</code> input array.</p>
*
* <p>A negative startIndex is treated as zero. A startIndex larger than the array
* length will return {@link #INDEX_NOT_FOUND} (<code>-1</code>).</p>
*
* @param array the array to search through for the object, may be <code>null</code>
* @param valueToFind the value to find
* @param startIndex the index to start searching at
* @return the index of the value within the array,
* {@link #INDEX_NOT_FOUND} (<code>-1</code>) if not found or <code>null</code> array input
*/
public static int indexOf(long[] array, long valueToFind, int startIndex) {
if (array == null) {
return -1;
}
if (startIndex < 0) {
startIndex = 0;
}
for (int i = startIndex; i < array.length; i++) {
if (valueToFind == array[i]) {
return i;
}
}
return -1;
}
/**
* <p>Finds the last index of the given value within the array.</p>
*
* <p>This method returns {@link #INDEX_NOT_FOUND} (<code>-1</code>) for a <code>null</code> input array.</p>
*
* @param array the array to travers backwords looking for the object, may be <code>null</code>
* @param valueToFind the object to find
* @return the last index of the value within the array,
* {@link #INDEX_NOT_FOUND} (<code>-1</code>) if not found or <code>null</code> array input
*/
public static int lastIndexOf(long[] array, long valueToFind) {
return lastIndexOf(array, valueToFind, Integer.MAX_VALUE);
}
/**
* <p>Finds the last index of the given value in the array starting at the given index.</p>
*
* <p>This method returns {@link #INDEX_NOT_FOUND} (<code>-1</code>) for a <code>null</code> input array.</p>
*
* <p>A negative startIndex will return {@link #INDEX_NOT_FOUND} (<code>-1</code>). A startIndex larger than the
* array length will search from the end of the array.</p>
*
* @param array the array to traverse for looking for the object, may be <code>null</code>
* @param valueToFind the value to find
* @param startIndex the start index to travers backwards from
* @return the last index of the value within the array,
* {@link #INDEX_NOT_FOUND} (<code>-1</code>) if not found or <code>null</code> array input
*/
public static int lastIndexOf(long[] array, long valueToFind, int startIndex) {
if (array == null) {
return -1;
}
if (startIndex < 0) {
return -1;
} else if (startIndex >= array.length) {
startIndex = array.length - 1;
}
for (int i = startIndex; i >= 0; i--) {
if (valueToFind == array[i]) {
return i;
}
}
return -1;
}
/**
* <p>Checks if the value is in the given array.</p>
*
* <p>The method returns <code>false</code> if a <code>null</code> array is passed in.</p>
*
* @param array the array to search through
* @param valueToFind the value to find
* @return <code>true</code> if the array contains the object
*/
public static boolean contains(long[] array, long valueToFind) {
return indexOf(array, valueToFind) != -1;
}
}
Get the element index and last index in a float type value array
/* Copyright 2004 The Apache Software Foundation
*
* 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.
*/
import java.lang.reflect.Array;
/**
* <p>Operations on arrays, primitive arrays (like <code>int[]</code>) and
* primitive wrapper arrays (like <code>Integer[]</code>).</p>
*
* <p>This class tries to handle <code>null</code> input gracefully.
* An exception will not be thrown for a <code>null</code>
* array input. However, an Object array that contains a <code>null</code>
* element may throw an exception. Each method documents its behaviour.</p>
*
* @author Stephen Colebourne
* @author Moritz Petersen
* @author
* @author Maarten Coene
* @since 2.0
* @version $Id: ArrayUtils.java 632503 2008-03-01 00:21:52Z ggregory $
*/
public class Main {
/**
* The index value when an element is not found in a list or array: <code>-1</code>.
* This value is returned by methods in this class and can also be used in comparisons with values returned by
* various method from {@link java.util.List}.
*/
public static final int INDEX_NOT_FOUND = -1;
// float IndexOf
//-----------------------------------------------------------------------
/**
* <p>Finds the index of the given value in the array.</p>
*
* <p>This method returns {@link #INDEX_NOT_FOUND} (<code>-1</code>) for a <code>null</code> input array.</p>
*
* @param array the array to search through for the object, may be <code>null</code>
* @param valueToFind the value to find
* @return the index of the value within the array,
* {@link #INDEX_NOT_FOUND} (<code>-1</code>) if not found or <code>null</code> array input
*/
public static int indexOf(float[] array, float valueToFind) {
return indexOf(array, valueToFind, 0);
}
/**
* <p>Finds the index of the given value in the array starting at the given index.</p>
*
* <p>This method returns {@link #INDEX_NOT_FOUND} (<code>-1</code>) for a <code>null</code> input array.</p>
*
* <p>A negative startIndex is treated as zero. A startIndex larger than the array
* length will return {@link #INDEX_NOT_FOUND} (<code>-1</code>).</p>
*
* @param array the array to search through for the object, may be <code>null</code>
* @param valueToFind the value to find
* @param startIndex the index to start searching at
* @return the index of the value within the array,
* {@link #INDEX_NOT_FOUND} (<code>-1</code>) if not found or <code>null</code> array input
*/
public static int indexOf(float[] array, float valueToFind, int startIndex) {
if (isEmpty(array)) {
return INDEX_NOT_FOUND;
}
if (startIndex < 0) {
startIndex = 0;
}
for (int i = startIndex; i < array.length; i++) {
if (valueToFind == array[i]) {
return i;
}
}
return INDEX_NOT_FOUND;
}
/**
* <p>Finds the last index of the given value within the array.</p>
*
* <p>This method returns {@link #INDEX_NOT_FOUND} (<code>-1</code>) for a <code>null</code> input array.</p>
*
* @param array the array to travers backwords looking for the object, may be <code>null</code>
* @param valueToFind the object to find
* @return the last index of the value within the array,
* {@link #INDEX_NOT_FOUND} (<code>-1</code>) if not found or <code>null</code> array input
*/
public static int lastIndexOf(float[] array, float valueToFind) {
return lastIndexOf(array, valueToFind, Integer.MAX_VALUE);
}
/**
* <p>Finds the last index of the given value in the array starting at the given index.</p>
*
* <p>This method returns {@link #INDEX_NOT_FOUND} (<code>-1</code>) for a <code>null</code> input array.</p>
*
* <p>A negative startIndex will return {@link #INDEX_NOT_FOUND} (<code>-1</code>). A startIndex larger than the
* array length will search from the end of the array.</p>
*
* @param array the array to traverse for looking for the object, may be <code>null</code>
* @param valueToFind the value to find
* @param startIndex the start index to travers backwards from
* @return the last index of the value within the array,
* {@link #INDEX_NOT_FOUND} (<code>-1</code>) if not found or <code>null</code> array input
*/
public static int lastIndexOf(float[] array, float valueToFind, int startIndex) {
if (isEmpty(array)) {
return INDEX_NOT_FOUND;
}
if (startIndex < 0) {
return INDEX_NOT_FOUND;
} else if (startIndex >= array.length) {
startIndex = array.length - 1;
}
for (int i = startIndex; i >= 0; i--) {
if (valueToFind == array[i]) {
return i;
}
}
return INDEX_NOT_FOUND;
}
/**
* <p>Checks if the value is in the given array.</p>
*
* <p>The method returns <code>false</code> if a <code>null</code> array is passed in.</p>
*
* @param array the array to search through
* @param valueToFind the value to find
* @return <code>true</code> if the array contains the object
*/
public static boolean contains(float[] array, float valueToFind) {
return indexOf(array, valueToFind) != INDEX_NOT_FOUND;
}
/**
* <p>Checks if an array of primitive doubles is empty or <code>null</code>.</p>
*
* @param array the array to test
* @return <code>true</code> if the array is empty or <code>null</code>
* @since 2.1
*/
public static boolean isEmpty(float[] array) {
if (array == null || array.length == 0) {
return true;
}
return false;
}
}
Get the element index or last index among a boolean type array
/* Copyright 2004 The Apache Software Foundation
*
* 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.
*/
import java.lang.reflect.Array;
/**
* <p>Operations on arrays, primitive arrays (like <code>int[]</code>) and
* primitive wrapper arrays (like <code>Integer[]</code>).</p>
*
* <p>This class tries to handle <code>null</code> input gracefully.
* An exception will not be thrown for a <code>null</code>
* array input. However, an Object array that contains a <code>null</code>
* element may throw an exception. Each method documents its behaviour.</p>
*
* @author Stephen Colebourne
* @author Moritz Petersen
* @author
* @author Maarten Coene
* @since 2.0
* @version $Id: ArrayUtils.java 632503 2008-03-01 00:21:52Z ggregory $
*/
public class Main {
/**
* The index value when an element is not found in a list or array: <code>-1</code>.
* This value is returned by methods in this class and can also be used in comparisons with values returned by
* various method from {@link java.util.List}.
*/
public static final int INDEX_NOT_FOUND = -1;
// boolean IndexOf
//-----------------------------------------------------------------------
/**
* <p>Finds the index of the given value in the array.</p>
*
* <p>This method returns {@link #INDEX_NOT_FOUND} (<code>-1</code>) for a <code>null</code> input array.</p>
*
* @param array the array to search through for the object, may be <code>null</code>
* @param valueToFind the value to find
* @return the index of the value within the array,
* {@link #INDEX_NOT_FOUND} (<code>-1</code>) if not found or <code>null</code> array input
*/
public static int indexOf(boolean[] array, boolean valueToFind) {
return indexOf(array, valueToFind, 0);
}
/**
* <p>Finds the index of the given value in the array starting at the given index.</p>
*
* <p>This method returns {@link #INDEX_NOT_FOUND} (<code>-1</code>) for a <code>null</code> input array.</p>
*
* <p>A negative startIndex is treated as zero. A startIndex larger than the array
* length will return {@link #INDEX_NOT_FOUND} (<code>-1</code>).</p>
*
* @param array the array to search through for the object, may be <code>null</code>
* @param valueToFind the value to find
* @param startIndex the index to start searching at
* @return the index of the value within the array,
* {@link #INDEX_NOT_FOUND} (<code>-1</code>) if not found or <code>null</code>
* array input
*/
public static int indexOf(boolean[] array, boolean valueToFind, int startIndex) {
if (isEmpty(array)) {
return INDEX_NOT_FOUND;
}
if (startIndex < 0) {
startIndex = 0;
}
for (int i = startIndex; i < array.length; i++) {
if (valueToFind == array[i]) {
return i;
}
}
return INDEX_NOT_FOUND;
}
/**
* <p>Finds the last index of the given value within the array.</p>
*
* <p>This method returns {@link #INDEX_NOT_FOUND} (<code>-1</code>) if
* <code>null</code> array input.</p>
*
* @param array the array to travers backwords looking for the object, may be <code>null</code>
* @param valueToFind the object to find
* @return the last index of the value within the array,
* {@link #INDEX_NOT_FOUND} (<code>-1</code>) if not found or <code>null</code> array input
*/
public static int lastIndexOf(boolean[] array, boolean valueToFind) {
return lastIndexOf(array, valueToFind, Integer.MAX_VALUE);
}
/**
* <p>Finds the last index of the given value in the array starting at the given index.</p>
*
* <p>This method returns {@link #INDEX_NOT_FOUND} (<code>-1</code>) for a <code>null</code> input array.</p>
*
* <p>A negative startIndex will return {@link #INDEX_NOT_FOUND} (<code>-1</code>). A startIndex larger than
* the array length will search from the end of the array.</p>
*
* @param array the array to traverse for looking for the object, may be <code>null</code>
* @param valueToFind the value to find
* @param startIndex the start index to travers backwards from
* @return the last index of the value within the array,
* {@link #INDEX_NOT_FOUND} (<code>-1</code>) if not found or <code>null</code> array input
*/
public static int lastIndexOf(boolean[] array, boolean valueToFind, int startIndex) {
if (isEmpty(array)) {
return INDEX_NOT_FOUND;
}
if (startIndex < 0) {
return INDEX_NOT_FOUND;
} else if (startIndex >= array.length) {
startIndex = array.length - 1;
}
for (int i = startIndex; i >= 0; i--) {
if (valueToFind == array[i]) {
return i;
}
}
return INDEX_NOT_FOUND;
}
/**
* <p>Checks if the value is in the given array.</p>
*
* <p>The method returns <code>false</code> if a <code>null</code> array is passed in.</p>
*
* @param array the array to search through
* @param valueToFind the value to find
* @return <code>true</code> if the array contains the object
*/
public static boolean contains(boolean[] array, boolean valueToFind) {
return indexOf(array, valueToFind) != INDEX_NOT_FOUND;
}
/**
* <p>Checks if an array of primitive doubles is empty or <code>null</code>.</p>
*
* @param array the array to test
* @return <code>true</code> if the array is empty or <code>null</code>
* @since 2.1
*/
public static boolean isEmpty(boolean[] array) {
if (array == null || array.length == 0) {
return true;
}
return false;
}
}
Get the index and last index of a char type value array
/* Copyright 2004 The Apache Software Foundation
*
* 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.
*/
import java.lang.reflect.Array;
/**
* <p>Operations on arrays, primitive arrays (like <code>int[]</code>) and
* primitive wrapper arrays (like <code>Integer[]</code>).</p>
*
* <p>This class tries to handle <code>null</code> input gracefully.
* An exception will not be thrown for a <code>null</code>
* array input. However, an Object array that contains a <code>null</code>
* element may throw an exception. Each method documents its behaviour.</p>
*
* @author Stephen Colebourne
* @author Moritz Petersen
* @author
* @author Maarten Coene
* @since 2.0
* @version $Id: ArrayUtils.java 632503 2008-03-01 00:21:52Z ggregory $
*/
public class Main {
/**
* The index value when an element is not found in a list or array: <code>-1</code>.
* This value is returned by methods in this class and can also be used in comparisons with values returned by
* various method from {@link java.util.List}.
*/
public static final int INDEX_NOT_FOUND = -1;
// char IndexOf
//-----------------------------------------------------------------------
/**
* <p>Finds the index of the given value in the array.</p>
*
* <p>This method returns {@link #INDEX_NOT_FOUND} (<code>-1</code>) for a <code>null</code> input array.</p>
*
* @param array the array to search through for the object, may be <code>null</code>
* @param valueToFind the value to find
* @return the index of the value within the array,
* {@link #INDEX_NOT_FOUND} (<code>-1</code>) if not found or <code>null</code> array input
* @since 2.1
*/
public static int indexOf(char[] array, char valueToFind) {
return indexOf(array, valueToFind, 0);
}
/**
* <p>Finds the index of the given value in the array starting at the given index.</p>
*
* <p>This method returns {@link #INDEX_NOT_FOUND} (<code>-1</code>) for a <code>null</code> input array.</p>
*
* <p>A negative startIndex is treated as zero. A startIndex larger than the array
* length will return {@link #INDEX_NOT_FOUND} (<code>-1</code>).</p>
*
* @param array the array to search through for the object, may be <code>null</code>
* @param valueToFind the value to find
* @param startIndex the index to start searching at
* @return the index of the value within the array,
* {@link #INDEX_NOT_FOUND} (<code>-1</code>) if not found or <code>null</code> array input
* @since 2.1
*/
public static int indexOf(char[] array, char valueToFind, int startIndex) {
if (array == null) {
return INDEX_NOT_FOUND;
}
if (startIndex < 0) {
startIndex = 0;
}
for (int i = startIndex; i < array.length; i++) {
if (valueToFind == array[i]) {
return i;
}
}
return INDEX_NOT_FOUND;
}
/**
* <p>Finds the last index of the given value within the array.</p>
*
* <p>This method returns {@link #INDEX_NOT_FOUND} (<code>-1</code>) for a <code>null</code> input array.</p>
*
* @param array the array to travers backwords looking for the object, may be <code>null</code>
* @param valueToFind the object to find
* @return the last index of the value within the array,
* {@link #INDEX_NOT_FOUND} (<code>-1</code>) if not found or <code>null</code> array input
* @since 2.1
*/
public static int lastIndexOf(char[] array, char valueToFind) {
return lastIndexOf(array, valueToFind, Integer.MAX_VALUE);
}
/**
* <p>Finds the last index of the given value in the array starting at the given index.</p>
*
* <p>This method returns {@link #INDEX_NOT_FOUND} (<code>-1</code>) for a <code>null</code> input array.</p>
*
* <p>A negative startIndex will return {@link #INDEX_NOT_FOUND} (<code>-1</code>). A startIndex larger than the
* array length will search from the end of the array.</p>
*
* @param array the array to traverse for looking for the object, may be <code>null</code>
* @param valueToFind the value to find
* @param startIndex the start index to travers backwards from
* @return the last index of the value within the array,
* {@link #INDEX_NOT_FOUND} (<code>-1</code>) if not found or <code>null</code> array input
* @since 2.1
*/
public static int lastIndexOf(char[] array, char valueToFind, int startIndex) {
if (array == null) {
return INDEX_NOT_FOUND;
}
if (startIndex < 0) {
return INDEX_NOT_FOUND;
} else if (startIndex >= array.length) {
startIndex = array.length - 1;
}
for (int i = startIndex; i >= 0; i--) {
if (valueToFind == array[i]) {
return i;
}
}
return INDEX_NOT_FOUND;
}
/**
* <p>Checks if the value is in the given array.</p>
*
* <p>The method returns <code>false</code> if a <code>null</code> array is passed in.</p>
*
* @param array the array to search through
* @param valueToFind the value to find
* @return <code>true</code> if the array contains the object
* @since 2.1
*/
public static boolean contains(char[] array, char valueToFind) {
return indexOf(array, valueToFind) != INDEX_NOT_FOUND;
}
}
Get the index and last index of a double type array
/* Copyright 2004 The Apache Software Foundation
*
* 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.
*/
import java.lang.reflect.Array;
/**
* <p>Operations on arrays, primitive arrays (like <code>int[]</code>) and
* primitive wrapper arrays (like <code>Integer[]</code>).</p>
*
* <p>This class tries to handle <code>null</code> input gracefully.
* An exception will not be thrown for a <code>null</code>
* array input. However, an Object array that contains a <code>null</code>
* element may throw an exception. Each method documents its behaviour.</p>
*
* @author Stephen Colebourne
* @author Moritz Petersen
* @author
* @author Maarten Coene
* @since 2.0
* @version $Id: ArrayUtils.java 632503 2008-03-01 00:21:52Z ggregory $
*/
public class Main {
/**
* The index value when an element is not found in a list or array: <code>-1</code>.
* This value is returned by methods in this class and can also be used in comparisons with values returned by
* various method from {@link java.util.List}.
*/
public static final int INDEX_NOT_FOUND = -1;
// double IndexOf
//-----------------------------------------------------------------------
/**
* <p>Finds the index of the given value in the array.</p>
*
* <p>This method returns {@link #INDEX_NOT_FOUND} (<code>-1</code>) for a <code>null</code> input array.</p>
*
* @param array the array to search through for the object, may be <code>null</code>
* @param valueToFind the value to find
* @return the index of the value within the array,
* {@link #INDEX_NOT_FOUND} (<code>-1</code>) if not found or <code>null</code> array input
*/
public static int indexOf(double[] array, double valueToFind) {
return indexOf(array, valueToFind, 0);
}
/**
* <p>Finds the index of the given value within a given tolerance in the array.
* This method will return the index of the first value which falls between the region
* defined by valueToFind - tolerance and valueToFind + tolerance.</p>
*
* <p>This method returns {@link #INDEX_NOT_FOUND} (<code>-1</code>) for a <code>null</code> input array.</p>
*
* @param array the array to search through for the object, may be <code>null</code>
* @param valueToFind the value to find
* @param tolerance tolerance of the search
* @return the index of the value within the array,
* {@link #INDEX_NOT_FOUND} (<code>-1</code>) if not found or <code>null</code> array input
*/
public static int indexOf(double[] array, double valueToFind, double tolerance) {
return indexOf(array, valueToFind, 0, tolerance);
}
/**
* <p>Finds the index of the given value in the array starting at the given index.</p>
*
* <p>This method returns {@link #INDEX_NOT_FOUND} (<code>-1</code>) for a <code>null</code> input array.</p>
*
* <p>A negative startIndex is treated as zero. A startIndex larger than the array
* length will return {@link #INDEX_NOT_FOUND} (<code>-1</code>).</p>
*
* @param array the array to search through for the object, may be <code>null</code>
* @param valueToFind the value to find
* @param startIndex the index to start searching at
* @return the index of the value within the array,
* {@link #INDEX_NOT_FOUND} (<code>-1</code>) if not found or <code>null</code> array input
*/
public static int indexOf(double[] array, double valueToFind, int startIndex) {
if (isEmpty(array)) {
return INDEX_NOT_FOUND;
}
if (startIndex < 0) {
startIndex = 0;
}
for (int i = startIndex; i < array.length; i++) {
if (valueToFind == array[i]) {
return i;
}
}
return INDEX_NOT_FOUND;
}
/**
* <p>Finds the index of the given value in the array starting at the given index.
* This method will return the index of the first value which falls between the region
* defined by valueToFind - tolerance and valueToFind + tolerance.</p>
*
* <p>This method returns {@link #INDEX_NOT_FOUND} (<code>-1</code>) for a <code>null</code> input array.</p>
*
* <p>A negative startIndex is treated as zero. A startIndex larger than the array
* length will return {@link #INDEX_NOT_FOUND} (<code>-1</code>).</p>
*
* @param array the array to search through for the object, may be <code>null</code>
* @param valueToFind the value to find
* @param startIndex the index to start searching at
* @param tolerance tolerance of the search
* @return the index of the value within the array,
* {@link #INDEX_NOT_FOUND} (<code>-1</code>) if not found or <code>null</code> array input
*/
public static int indexOf(double[] array, double valueToFind, int startIndex, double tolerance) {
if (isEmpty(array)) {
return INDEX_NOT_FOUND;
}
if (startIndex < 0) {
startIndex = 0;
}
double min = valueToFind - tolerance;
double max = valueToFind + tolerance;
for (int i = startIndex; i < array.length; i++) {
if (array[i] >= min && array[i] <= max) {
return i;
}
}
return INDEX_NOT_FOUND;
}
/**
* <p>Finds the last index of the given value within the array.</p>
*
* <p>This method returns {@link #INDEX_NOT_FOUND} (<code>-1</code>) for a <code>null</code> input array.</p>
*
* @param array the array to travers backwords looking for the object, may be <code>null</code>
* @param valueToFind the object to find
* @return the last index of the value within the array,
* {@link #INDEX_NOT_FOUND} (<code>-1</code>) if not found or <code>null</code> array input
*/
public static int lastIndexOf(double[] array, double valueToFind) {
return lastIndexOf(array, valueToFind, Integer.MAX_VALUE);
}
/**
* <p>Finds the last index of the given value within a given tolerance in the array.
* This method will return the index of the last value which falls between the region
* defined by valueToFind - tolerance and valueToFind + tolerance.</p>
*
* <p>This method returns {@link #INDEX_NOT_FOUND} (<code>-1</code>) for a <code>null</code> input array.</p>
*
* @param array the array to search through for the object, may be <code>null</code>
* @param valueToFind the value to find
* @param tolerance tolerance of the search
* @return the index of the value within the array,
* {@link #INDEX_NOT_FOUND} (<code>-1</code>) if not found or <code>null</code> array input
*/
public static int lastIndexOf(double[] array, double valueToFind, double tolerance) {
return lastIndexOf(array, valueToFind, Integer.MAX_VALUE, tolerance);
}
/**
* <p>Finds the last index of the given value in the array starting at the given index.</p>
*
* <p>This method returns {@link #INDEX_NOT_FOUND} (<code>-1</code>) for a <code>null</code> input array.</p>
*
* <p>A negative startIndex will return {@link #INDEX_NOT_FOUND} (<code>-1</code>). A startIndex larger than the
* array length will search from the end of the array.</p>
*
* @param array the array to traverse for looking for the object, may be <code>null</code>
* @param valueToFind the value to find
* @param startIndex the start index to travers backwards from
* @return the last index of the value within the array,
* {@link #INDEX_NOT_FOUND} (<code>-1</code>) if not found or <code>null</code> array input
*/
public static int lastIndexOf(double[] array, double valueToFind, int startIndex) {
if (isEmpty(array)) {
return INDEX_NOT_FOUND;
}
if (startIndex < 0) {
return INDEX_NOT_FOUND;
} else if (startIndex >= array.length) {
startIndex = array.length - 1;
}
for (int i = startIndex; i >= 0; i--) {
if (valueToFind == array[i]) {
return i;
}
}
return INDEX_NOT_FOUND;
}
/**
* <p>Finds the last index of the given value in the array starting at the given index.
* This method will return the index of the last value which falls between the region
* defined by valueToFind - tolerance and valueToFind + tolerance.</p>
*
* <p>This method returns {@link #INDEX_NOT_FOUND} (<code>-1</code>) for a <code>null</code> input array.</p>
*
* <p>A negative startIndex will return {@link #INDEX_NOT_FOUND} (<code>-1</code>). A startIndex larger than the
* array length will search from the end of the array.</p>
*
* @param array the array to traverse for looking for the object, may be <code>null</code>
* @param valueToFind the value to find
* @param startIndex the start index to travers backwards from
* @param tolerance search for value within plus/minus this amount
* @return the last index of the value within the array,
* {@link #INDEX_NOT_FOUND} (<code>-1</code>) if not found or <code>null</code> array input
*/
public static int lastIndexOf(double[] array, double valueToFind, int startIndex, double tolerance) {
if (isEmpty(array)) {
return INDEX_NOT_FOUND;
}
if (startIndex < 0) {
return INDEX_NOT_FOUND;
} else if (startIndex >= array.length) {
startIndex = array.length - 1;
}
double min = valueToFind - tolerance;
double max = valueToFind + tolerance;
for (int i = startIndex; i >= 0; i--) {
if (array[i] >= min && array[i] <= max) {
return i;
}
}
return INDEX_NOT_FOUND;
}
/**
* <p>Checks if the value is in the given array.</p>
*
* <p>The method returns <code>false</code> if a <code>null</code> array is passed in.</p>
*
* @param array the array to search through
* @param valueToFind the value to find
* @return <code>true</code> if the array contains the object
*/
public static boolean contains(double[] array, double valueToFind) {
return indexOf(array, valueToFind) != INDEX_NOT_FOUND;
}
/**
* <p>Checks if a value falling within the given tolerance is in the
* given array. If the array contains a value within the inclusive range
* defined by (value - tolerance) to (value + tolerance).</p>
*
* <p>The method returns <code>false</code> if a <code>null</code> array
* is passed in.</p>
*
* @param array the array to search
* @param valueToFind the value to find
* @param tolerance the array contains the tolerance of the search
* @return true if value falling within tolerance is in array
*/
public static boolean contains(double[] array, double valueToFind, double tolerance) {
return indexOf(array, valueToFind, 0, tolerance) != INDEX_NOT_FOUND;
}
/**
* <p>Checks if an array of primitive doubles is empty or <code>null</code>.</p>
*
* @param array the array to test
* @return <code>true</code> if the array is empty or <code>null</code>
* @since 2.1
*/
public static boolean isEmpty(double[] array) {
if (array == null || array.length == 0) {
return true;
}
return false;
}
}
Get the index and last index of an int type value array
/* Copyright 2004 The Apache Software Foundation
*
* 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.
*/
import java.lang.reflect.Array;
/**
* <p>Operations on arrays, primitive arrays (like <code>int[]</code>) and
* primitive wrapper arrays (like <code>Integer[]</code>).</p>
*
* <p>This class tries to handle <code>null</code> input gracefully.
* An exception will not be thrown for a <code>null</code>
* array input. However, an Object array that contains a <code>null</code>
* element may throw an exception. Each method documents its behaviour.</p>
*
* @author Stephen Colebourne
* @author Moritz Petersen
* @author
* @author Maarten Coene
* @since 2.0
* @version $Id: ArrayUtils.java 632503 2008-03-01 00:21:52Z ggregory $
*/
public class Main {
/**
* The index value when an element is not found in a list or array: <code>-1</code>.
* This value is returned by methods in this class and can also be used in comparisons with values returned by
* various method from {@link java.util.List}.
*/
public static final int INDEX_NOT_FOUND = -1;
// int IndexOf
//-----------------------------------------------------------------------
/**
* <p>Finds the index of the given value in the array.</p>
*
* <p>This method returns {@link #INDEX_NOT_FOUND} (<code>-1</code>) for a <code>null</code> input array.</p>
*
* @param array the array to search through for the object, may be <code>null</code>
* @param valueToFind the value to find
* @return the index of the value within the array,
* {@link #INDEX_NOT_FOUND} (<code>-1</code>) if not found or <code>null</code> array input
*/
public static int indexOf(int[] array, int valueToFind) {
return indexOf(array, valueToFind, 0);
}
/**
* <p>Finds the index of the given value in the array starting at the given index.</p>
*
* <p>This method returns {@link #INDEX_NOT_FOUND} (<code>-1</code>) for a <code>null</code> input array.</p>
*
* <p>A negative startIndex is treated as zero. A startIndex larger than the array
* length will return {@link #INDEX_NOT_FOUND} (<code>-1</code>).</p>
*
* @param array the array to search through for the object, may be <code>null</code>
* @param valueToFind the value to find
* @param startIndex the index to start searching at
* @return the index of the value within the array,
* {@link #INDEX_NOT_FOUND} (<code>-1</code>) if not found or <code>null</code> array input
*/
public static int indexOf(int[] array, int valueToFind, int startIndex) {
if (array == null) {
return INDEX_NOT_FOUND;
}
if (startIndex < 0) {
startIndex = 0;
}
for (int i = startIndex; i < array.length; i++) {
if (valueToFind == array[i]) {
return i;
}
}
return INDEX_NOT_FOUND;
}
/**
* <p>Finds the last index of the given value within the array.</p>
*
* <p>This method returns {@link #INDEX_NOT_FOUND} (<code>-1</code>) for a <code>null</code> input array.</p>
*
* @param array the array to travers backwords looking for the object, may be <code>null</code>
* @param valueToFind the object to find
* @return the last index of the value within the array,
* {@link #INDEX_NOT_FOUND} (<code>-1</code>) if not found or <code>null</code> array input
*/
public static int lastIndexOf(int[] array, int valueToFind) {
return lastIndexOf(array, valueToFind, Integer.MAX_VALUE);
}
/**
* <p>Finds the last index of the given value in the array starting at the given index.</p>
*
* <p>This method returns {@link #INDEX_NOT_FOUND} (<code>-1</code>) for a <code>null</code> input array.</p>
*
* <p>A negative startIndex will return {@link #INDEX_NOT_FOUND} (<code>-1</code>). A startIndex larger than the
* array length will search from the end of the array.</p>
*
* @param array the array to traverse for looking for the object, may be <code>null</code>
* @param valueToFind the value to find
* @param startIndex the start index to travers backwards from
* @return the last index of the value within the array,
* {@link #INDEX_NOT_FOUND} (<code>-1</code>) if not found or <code>null</code> array input
*/
public static int lastIndexOf(int[] array, int valueToFind, int startIndex) {
if (array == null) {
return INDEX_NOT_FOUND;
}
if (startIndex < 0) {
return INDEX_NOT_FOUND;
} else if (startIndex >= array.length) {
startIndex = array.length - 1;
}
for (int i = startIndex; i >= 0; i--) {
if (valueToFind == array[i]) {
return i;
}
}
return INDEX_NOT_FOUND;
}
/**
* <p>Checks if the value is in the given array.</p>
*
* <p>The method returns <code>false</code> if a <code>null</code> array is passed in.</p>
*
* @param array the array to search through
* @param valueToFind the value to find
* @return <code>true</code> if the array contains the object
*/
public static boolean contains(int[] array, int valueToFind) {
return indexOf(array, valueToFind) != INDEX_NOT_FOUND;
}
}
Get the index and last index of a short type value array
/* Copyright 2004 The Apache Software Foundation
*
* 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.
*/
import java.lang.reflect.Array;
/**
* <p>Operations on arrays, primitive arrays (like <code>int[]</code>) and
* primitive wrapper arrays (like <code>Integer[]</code>).</p>
*
* <p>This class tries to handle <code>null</code> input gracefully.
* An exception will not be thrown for a <code>null</code>
* array input. However, an Object array that contains a <code>null</code>
* element may throw an exception. Each method documents its behaviour.</p>
*
* @author Stephen Colebourne
* @author Moritz Petersen
* @author
* @author Maarten Coene
* @since 2.0
* @version $Id: ArrayUtils.java 632503 2008-03-01 00:21:52Z ggregory $
*/
public class Main {
/**
* The index value when an element is not found in a list or array: <code>-1</code>.
* This value is returned by methods in this class and can also be used in comparisons with values returned by
* various method from {@link java.util.List}.
*/
public static final int INDEX_NOT_FOUND = -1;
// short IndexOf
//-----------------------------------------------------------------------
/**
* <p>Finds the index of the given value in the array.</p>
*
* <p>This method returns {@link #INDEX_NOT_FOUND} (<code>-1</code>) for a <code>null</code> input array.</p>
*
* @param array the array to search through for the object, may be <code>null</code>
* @param valueToFind the value to find
* @return the index of the value within the array,
* {@link #INDEX_NOT_FOUND} (<code>-1</code>) if not found or <code>null</code> array input
*/
public static int indexOf(short[] array, short valueToFind) {
return indexOf(array, valueToFind, 0);
}
/**
* <p>Finds the index of the given value in the array starting at the given index.</p>
*
* <p>This method returns {@link #INDEX_NOT_FOUND} (<code>-1</code>) for a <code>null</code> input array.</p>
*
* <p>A negative startIndex is treated as zero. A startIndex larger than the array
* length will return {@link #INDEX_NOT_FOUND} (<code>-1</code>).</p>
*
* @param array the array to search through for the object, may be <code>null</code>
* @param valueToFind the value to find
* @param startIndex the index to start searching at
* @return the index of the value within the array,
* {@link #INDEX_NOT_FOUND} (<code>-1</code>) if not found or <code>null</code> array input
*/
public static int indexOf(short[] array, short valueToFind, int startIndex) {
if (array == null) {
return INDEX_NOT_FOUND;
}
if (startIndex < 0) {
startIndex = 0;
}
for (int i = startIndex; i < array.length; i++) {
if (valueToFind == array[i]) {
return i;
}
}
return INDEX_NOT_FOUND;
}
/**
* <p>Finds the last index of the given value within the array.</p>
*
* <p>This method returns {@link #INDEX_NOT_FOUND} (<code>-1</code>) for a <code>null</code> input array.</p>
*
* @param array the array to travers backwords looking for the object, may be <code>null</code>
* @param valueToFind the object to find
* @return the last index of the value within the array,
* {@link #INDEX_NOT_FOUND} (<code>-1</code>) if not found or <code>null</code> array input
*/
public static int lastIndexOf(short[] array, short valueToFind) {
return lastIndexOf(array, valueToFind, Integer.MAX_VALUE);
}
/**
* <p>Finds the last index of the given value in the array starting at the given index.</p>
*
* <p>This method returns {@link #INDEX_NOT_FOUND} (<code>-1</code>) for a <code>null</code> input array.</p>
*
* <p>A negative startIndex will return {@link #INDEX_NOT_FOUND} (<code>-1</code>). A startIndex larger than the
* array length will search from the end of the array.</p>
*
* @param array the array to traverse for looking for the object, may be <code>null</code>
* @param valueToFind the value to find
* @param startIndex the start index to travers backwards from
* @return the last index of the value within the array,
* {@link #INDEX_NOT_FOUND} (<code>-1</code>) if not found or <code>null</code> array input
*/
public static int lastIndexOf(short[] array, short valueToFind, int startIndex) {
if (array == null) {
return INDEX_NOT_FOUND;
}
if (startIndex < 0) {
return INDEX_NOT_FOUND;
} else if (startIndex >= array.length) {
startIndex = array.length - 1;
}
for (int i = startIndex; i >= 0; i--) {
if (valueToFind == array[i]) {
return i;
}
}
return INDEX_NOT_FOUND;
}
/**
* <p>Checks if the value is in the given array.</p>
*
* <p>The method returns <code>false</code> if a <code>null</code> array is passed in.</p>
*
* @param array the array to search through
* @param valueToFind the value to find
* @return <code>true</code> if the array contains the object
*/
public static boolean contains(short[] array, short valueToFind) {
return indexOf(array, valueToFind) != INDEX_NOT_FOUND;
}
}
Get the index and last index of byte type array
/* Copyright 2004 The Apache Software Foundation
*
* 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.
*/
import java.lang.reflect.Array;
/**
* <p>Operations on arrays, primitive arrays (like <code>int[]</code>) and
* primitive wrapper arrays (like <code>Integer[]</code>).</p>
*
* <p>This class tries to handle <code>null</code> input gracefully.
* An exception will not be thrown for a <code>null</code>
* array input. However, an Object array that contains a <code>null</code>
* element may throw an exception. Each method documents its behaviour.</p>
*
* @author Stephen Colebourne
* @author Moritz Petersen
* @author
* @author Maarten Coene
* @since 2.0
* @version $Id: ArrayUtils.java 632503 2008-03-01 00:21:52Z ggregory $
*/
public class Main {
/**
* The index value when an element is not found in a list or array: <code>-1</code>.
* This value is returned by methods in this class and can also be used in comparisons with values returned by
* various method from {@link java.util.List}.
*/
public static final int INDEX_NOT_FOUND = -1;
// byte IndexOf
//-----------------------------------------------------------------------
/**
* <p>Finds the index of the given value in the array.</p>
*
* <p>This method returns {@link #INDEX_NOT_FOUND} (<code>-1</code>) for a <code>null</code> input array.</p>
*
* @param array the array to search through for the object, may be <code>null</code>
* @param valueToFind the value to find
* @return the index of the value within the array,
* {@link #INDEX_NOT_FOUND} (<code>-1</code>) if not found or <code>null</code> array input
*/
public static int indexOf(byte[] array, byte valueToFind) {
return indexOf(array, valueToFind, 0);
}
/**
* <p>Finds the index of the given value in the array starting at the given index.</p>
*
* <p>This method returns {@link #INDEX_NOT_FOUND} (<code>-1</code>) for a <code>null</code> input array.</p>
*
* <p>A negative startIndex is treated as zero. A startIndex larger than the array
* length will return {@link #INDEX_NOT_FOUND} (<code>-1</code>).</p>
*
* @param array the array to search through for the object, may be <code>null</code>
* @param valueToFind the value to find
* @param startIndex the index to start searching at
* @return the index of the value within the array,
* {@link #INDEX_NOT_FOUND} (<code>-1</code>) if not found or <code>null</code> array input
*/
public static int indexOf(byte[] array, byte valueToFind, int startIndex) {
if (array == null) {
return INDEX_NOT_FOUND;
}
if (startIndex < 0) {
startIndex = 0;
}
for (int i = startIndex; i < array.length; i++) {
if (valueToFind == array[i]) {
return i;
}
}
return INDEX_NOT_FOUND;
}
/**
* <p>Finds the last index of the given value within the array.</p>
*
* <p>This method returns {@link #INDEX_NOT_FOUND} (<code>-1</code>) for a <code>null</code> input array.</p>
*
* @param array the array to travers backwords looking for the object, may be <code>null</code>
* @param valueToFind the object to find
* @return the last index of the value within the array,
* {@link #INDEX_NOT_FOUND} (<code>-1</code>) if not found or <code>null</code> array input
*/
public static int lastIndexOf(byte[] array, byte valueToFind) {
return lastIndexOf(array, valueToFind, Integer.MAX_VALUE);
}
/**
* <p>Finds the last index of the given value in the array starting at the given index.</p>
*
* <p>This method returns {@link #INDEX_NOT_FOUND} (<code>-1</code>) for a <code>null</code> input array.</p>
*
* <p>A negative startIndex will return {@link #INDEX_NOT_FOUND} (<code>-1</code>). A startIndex larger than the
* array length will search from the end of the array.</p>
*
* @param array the array to traverse for looking for the object, may be <code>null</code>
* @param valueToFind the value to find
* @param startIndex the start index to travers backwards from
* @return the last index of the value within the array,
* {@link #INDEX_NOT_FOUND} (<code>-1</code>) if not found or <code>null</code> array input
*/
public static int lastIndexOf(byte[] array, byte valueToFind, int startIndex) {
if (array == null) {
return INDEX_NOT_FOUND;
}
if (startIndex < 0) {
return INDEX_NOT_FOUND;
} else if (startIndex >= array.length) {
startIndex = array.length - 1;
}
for (int i = startIndex; i >= 0; i--) {
if (valueToFind == array[i]) {
return i;
}
}
return INDEX_NOT_FOUND;
}
/**
* <p>Checks if the value is in the given array.</p>
*
* <p>The method returns <code>false</code> if a <code>null</code> array is passed in.</p>
*
* @param array the array to search through
* @param valueToFind the value to find
* @return <code>true</code> if the array contains the object
*/
public static boolean contains(byte[] array, byte valueToFind) {
return indexOf(array, valueToFind) != INDEX_NOT_FOUND;
}
}
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 array contains given element
/*
* Copyright (c) 2003 - 2007 OpenSubsystems s.r.o. Slovak Republic. All rights reserved.
*
* Project: OpenSubsystems
*
* $Id: ArrayUtils.java,v 1.9 2007/01/23 06:00:30 bastafidli Exp $
*
* This program 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; version 2 of the License.
*
* This program 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 this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/**
* Collection of useful utilities to work with arrays.
*
* @version $Id: ArrayUtils.java,v 1.9 2007/01/23 06:00:30 bastafidli Exp $
* @author Peter Satury
* @code.reviewer Miro Halas
* @code.reviewed 1.5 2005/07/29 07:36:24 bastafidli
*/
public final class ArrayUtils
{
/**
* Private constructor since this class cannot be instantiated
*/
private ArrayUtils(
)
{
// Do nothing
}
// Public methods ///////////////////////////////////////////////////////////
/**
* Method to exclude 2 arrays of ints so that the result contains all elements
* from the first array, which are not in the second array.
*
* @param arrBase - base array to exclude from
* @param arrExclude - array to exclude from the first one
* @return int[] - array which contains all elements from the first array
* which are not in the second array or null
*/
public static int[] exclude(
int[] arrBase,
int[] arrExclude
)
{
int[] arrReturn = null;
if ((arrBase != null) && (arrBase.length > 0) && (arrExclude != null)
&& (arrExclude.length > 0))
{
int[] arrHelp;
int iCount1;
int iHelp;
int iLength = 0;
arrHelp = new int[arrBase.length];
for (iCount1 = 0; iCount1 < arrBase.length; iCount1++)
{
iHelp = arrBase[iCount1];
if (ArrayUtils.contains(arrExclude, iHelp) == -1)
{
// If the element is not part of the second array then it should
// be included in the result
arrHelp[iLength++] = iHelp;
}
}
// Shrink the array
// TODO: Performance: Replace this with System.arraycopy
arrReturn = new int[iLength];
for (int iCount = 0; iCount < iLength; iCount++)
{
arrReturn[iCount] = arrHelp[iCount];
}
}
else
{
arrReturn = arrBase;
}
return arrReturn;
}
/**
* Test if specified array contains given element and if it does, find
* its position.
*
* @param source - array to search, can be null
* @param iTarget - element to find
* @return int - -1 if it doesn"t exist there otherwise its position
*/
public static int contains(
int[] source,
int iTarget
)
{
int iReturn = -1;
if ((source != null) && (source.length > 0))
{
int iIndex;
for (iIndex = 0; iIndex < source.length; iIndex++)
{
if (source[iIndex] == iTarget)
{
iReturn = iIndex;
break;
}
}
}
return iReturn;
}
/**
* Sum all elements in the array.
*
* @param source - array to sum elements of
* @return long - sum of the elements in the array
*/
public static long sum(
int[] source
)
{
int iReturn = 0;
if ((source != null) && (source.length > 0))
{
int iIndex;
for (iIndex = 0; iIndex < source.length; iIndex++)
{
iReturn += source[iIndex];
}
}
return iReturn;
}
}
Inserting an Element into a Sorted Array
import java.util.Arrays;
public class Main {
public static void main(String[] argv) {
String[] oldArray = new String[] { "a", "b", "c", "d" };
int index = Arrays.binarySearch(oldArray, "e");
if (index < 0) {
int insertIndex = -index - 1;
String[] newArray = new String[oldArray.length + 1];
System.arraycopy(oldArray, 0, newArray, 0, insertIndex);
System.arraycopy(oldArray, insertIndex, newArray, insertIndex + 1,
oldArray.length - insertIndex);
newArray[insertIndex] = "e";
oldArray = newArray;
}
}
}
Produces a new array containing the elements between the start and end indices.
import java.lang.reflect.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.
*
*
*/
/**
* @author Stephen Colebourne
* @author Moritz Petersen
* @author
* @author Maarten Coene
* @since 2.0
* @version $Id: ArrayUtils.java 632503 2008-03-01 00:21:52Z ggregory $
*/
public class Main {
// Subarrays
//-----------------------------------------------------------------------
/**
* <p>Produces a new array containing the elements between
* the start and end indices.</p>
*
* <p>The start index is inclusive, the end index exclusive.
* Null array input produces null output.</p>
*
* <p>The component type of the subarray is always the same as
* that of the input array. Thus, if the input is an array of type
* <code>Date</code>, the following usage is envisaged:</p>
*
* <pre>
* Date[] someDates = (Date[])ArrayUtils.subarray(allDates, 2, 5);
* </pre>
*
* @param array the array
* @param startIndexInclusive the starting index. Undervalue (<0)
* is promoted to 0, overvalue (>array.length) results
* in an empty array.
* @param endIndexExclusive elements up to endIndex-1 are present in the
* returned subarray. Undervalue (< startIndex) produces
* empty array, overvalue (>array.length) is demoted to
* array length.
* @return a new array containing the elements between
* the start and end indices.
* @since 2.1
*/
public static Object[] subarray(Object[] array, int startIndexInclusive, int endIndexExclusive) {
if (array == null) {
return null;
}
if (startIndexInclusive < 0) {
startIndexInclusive = 0;
}
if (endIndexExclusive > array.length) {
endIndexExclusive = array.length;
}
int newSize = endIndexExclusive - startIndexInclusive;
Class type = array.getClass().getComponentType();
if (newSize <= 0) {
return (Object[]) Array.newInstance(type, 0);
}
Object[] subarray = (Object[]) Array.newInstance(type, newSize);
System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
return subarray;
}
}
Produces a new boolean array containing the elements between the start and end indices.
import java.lang.reflect.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.
*
*
*/
/**
* @author Stephen Colebourne
* @author Moritz Petersen
* @author
* @author Maarten Coene
* @since 2.0
* @version $Id: ArrayUtils.java 632503 2008-03-01 00:21:52Z ggregory $
*/
public class Main {
/**
* <p>Produces a new <code>boolean</code> array containing the elements
* between the start and end indices.</p>
*
* <p>The start index is inclusive, the end index exclusive.
* Null array input produces null output.</p>
*
* @param array the array
* @param startIndexInclusive the starting index. Undervalue (<0)
* is promoted to 0, overvalue (>array.length) results
* in an empty array.
* @param endIndexExclusive elements up to endIndex-1 are present in the
* returned subarray. Undervalue (< startIndex) produces
* empty array, overvalue (>array.length) is demoted to
* array length.
* @return a new array containing the elements between
* the start and end indices.
* @since 2.1
*/
public static boolean[] subarray(boolean[] array, int startIndexInclusive, int endIndexExclusive) {
if (array == null) {
return null;
}
if (startIndexInclusive < 0) {
startIndexInclusive = 0;
}
if (endIndexExclusive > array.length) {
endIndexExclusive = array.length;
}
int newSize = endIndexExclusive - startIndexInclusive;
if (newSize <= 0) {
return new boolean[0];
}
boolean[] subarray = new boolean[newSize];
System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
return subarray;
}
}
Produces a new byte array containing the elements between the start and end indices.
import java.lang.reflect.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.
*
*
*/
/**
* @author Stephen Colebourne
* @author Moritz Petersen
* @author
* @author Maarten Coene
* @since 2.0
* @version $Id: ArrayUtils.java 632503 2008-03-01 00:21:52Z ggregory $
*/
public class Main {
/**
* <p>Produces a new <code>byte</code> array containing the elements
* between the start and end indices.</p>
*
* <p>The start index is inclusive, the end index exclusive.
* Null array input produces null output.</p>
*
* @param array the array
* @param startIndexInclusive the starting index. Undervalue (<0)
* is promoted to 0, overvalue (>array.length) results
* in an empty array.
* @param endIndexExclusive elements up to endIndex-1 are present in the
* returned subarray. Undervalue (< startIndex) produces
* empty array, overvalue (>array.length) is demoted to
* array length.
* @return a new array containing the elements between
* the start and end indices.
* @since 2.1
*/
public static byte[] subarray(byte[] array, int startIndexInclusive, int endIndexExclusive) {
if (array == null) {
return null;
}
if (startIndexInclusive < 0) {
startIndexInclusive = 0;
}
if (endIndexExclusive > array.length) {
endIndexExclusive = array.length;
}
int newSize = endIndexExclusive - startIndexInclusive;
if (newSize <= 0) {
return new byte[0];
}
byte[] subarray = new byte[newSize];
System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
return subarray;
}
}
Produces a new char array containing the elements between the start and end indices.
import java.lang.reflect.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.
*
*
*/
/**
* @author Stephen Colebourne
* @author Moritz Petersen
* @author
* @author Maarten Coene
* @since 2.0
* @version $Id: ArrayUtils.java 632503 2008-03-01 00:21:52Z ggregory $
*/
public class Main {
/**
* <p>Produces a new <code>char</code> array containing the elements
* between the start and end indices.</p>
*
* <p>The start index is inclusive, the end index exclusive.
* Null array input produces null output.</p>
*
* @param array the array
* @param startIndexInclusive the starting index. Undervalue (<0)
* is promoted to 0, overvalue (>array.length) results
* in an empty array.
* @param endIndexExclusive elements up to endIndex-1 are present in the
* returned subarray. Undervalue (< startIndex) produces
* empty array, overvalue (>array.length) is demoted to
* array length.
* @return a new array containing the elements between
* the start and end indices.
* @since 2.1
*/
public static char[] subarray(char[] array, int startIndexInclusive, int endIndexExclusive) {
if (array == null) {
return null;
}
if (startIndexInclusive < 0) {
startIndexInclusive = 0;
}
if (endIndexExclusive > array.length) {
endIndexExclusive = array.length;
}
int newSize = endIndexExclusive - startIndexInclusive;
if (newSize <= 0) {
return new char[0];
}
char[] subarray = new char[newSize];
System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
return subarray;
}
}
Produces a new double array containing the elements between the start and end indices.
import java.lang.reflect.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.
*
*
*/
/**
* @author Stephen Colebourne
* @author Moritz Petersen
* @author
* @author Maarten Coene
* @since 2.0
* @version $Id: ArrayUtils.java 632503 2008-03-01 00:21:52Z ggregory $
*/
public class Main {
/**
* <p>Produces a new <code>double</code> array containing the elements
* between the start and end indices.</p>
*
* <p>The start index is inclusive, the end index exclusive.
* Null array input produces null output.</p>
*
* @param array the array
* @param startIndexInclusive the starting index. Undervalue (<0)
* is promoted to 0, overvalue (>array.length) results
* in an empty array.
* @param endIndexExclusive elements up to endIndex-1 are present in the
* returned subarray. Undervalue (< startIndex) produces
* empty array, overvalue (>array.length) is demoted to
* array length.
* @return a new array containing the elements between
* the start and end indices.
* @since 2.1
*/
public static double[] subarray(double[] array, int startIndexInclusive, int endIndexExclusive) {
if (array == null) {
return null;
}
if (startIndexInclusive < 0) {
startIndexInclusive = 0;
}
if (endIndexExclusive > array.length) {
endIndexExclusive = array.length;
}
int newSize = endIndexExclusive - startIndexInclusive;
if (newSize <= 0) {
return new double[0];
}
double[] subarray = new double[newSize];
System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
return subarray;
}
}
Produces a new float array containing the elements between the start and end indices.
import java.lang.reflect.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.
*
*
*/
/**
* @author Stephen Colebourne
* @author Moritz Petersen
* @author
* @author Maarten Coene
* @since 2.0
* @version $Id: ArrayUtils.java 632503 2008-03-01 00:21:52Z ggregory $
*/
public class Main {
/**
* <p>Produces a new <code>float</code> array containing the elements
* between the start and end indices.</p>
*
* <p>The start index is inclusive, the end index exclusive.
* Null array input produces null output.</p>
*
* @param array the array
* @param startIndexInclusive the starting index. Undervalue (<0)
* is promoted to 0, overvalue (>array.length) results
* in an empty array.
* @param endIndexExclusive elements up to endIndex-1 are present in the
* returned subarray. Undervalue (< startIndex) produces
* empty array, overvalue (>array.length) is demoted to
* array length.
* @return a new array containing the elements between
* the start and end indices.
* @since 2.1
*/
public static float[] subarray(float[] array, int startIndexInclusive, int endIndexExclusive) {
if (array == null) {
return null;
}
if (startIndexInclusive < 0) {
startIndexInclusive = 0;
}
if (endIndexExclusive > array.length) {
endIndexExclusive = array.length;
}
int newSize = endIndexExclusive - startIndexInclusive;
if (newSize <= 0) {
return new float[0];
}
float[] subarray = new float[newSize];
System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
return subarray;
}
}
Produces a new int array containing the elements between the start and end indices.
import java.lang.reflect.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.
*
*
*/
/**
* @author Stephen Colebourne
* @author Moritz Petersen
* @author
* @author Maarten Coene
* @since 2.0
* @version $Id: ArrayUtils.java 632503 2008-03-01 00:21:52Z ggregory $
*/
public class Main {
/**
* <p>Produces a new <code>int</code> array containing the elements
* between the start and end indices.</p>
*
* <p>The start index is inclusive, the end index exclusive.
* Null array input produces null output.</p>
*
* @param array the array
* @param startIndexInclusive the starting index. Undervalue (<0)
* is promoted to 0, overvalue (>array.length) results
* in an empty array.
* @param endIndexExclusive elements up to endIndex-1 are present in the
* returned subarray. Undervalue (< startIndex) produces
* empty array, overvalue (>array.length) is demoted to
* array length.
* @return a new array containing the elements between
* the start and end indices.
* @since 2.1
*/
public static int[] subarray(int[] array, int startIndexInclusive, int endIndexExclusive) {
if (array == null) {
return null;
}
if (startIndexInclusive < 0) {
startIndexInclusive = 0;
}
if (endIndexExclusive > array.length) {
endIndexExclusive = array.length;
}
int newSize = endIndexExclusive - startIndexInclusive;
if (newSize <= 0) {
return new int[0];
}
int[] subarray = new int[newSize];
System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
return subarray;
}
}
Produces a new long array containing the elements between the start and end indices.
import java.lang.reflect.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.
*
*
*/
/**
* @author Stephen Colebourne
* @author Moritz Petersen
* @author
* @author Maarten Coene
* @since 2.0
* @version $Id: ArrayUtils.java 632503 2008-03-01 00:21:52Z ggregory $
*/
public class Main {
/**
* <p>Produces a new <code>long</code> array containing the elements
* between the start and end indices.</p>
*
* <p>The start index is inclusive, the end index exclusive.
* Null array input produces null output.</p>
*
* @param array the array
* @param startIndexInclusive the starting index. Undervalue (<0)
* is promoted to 0, overvalue (>array.length) results
* in an empty array.
* @param endIndexExclusive elements up to endIndex-1 are present in the
* returned subarray. Undervalue (< startIndex) produces
* empty array, overvalue (>array.length) is demoted to
* array length.
* @return a new array containing the elements between
* the start and end indices.
* @since 2.1
*/
public static long[] subarray(long[] array, int startIndexInclusive, int endIndexExclusive) {
if (array == null) {
return null;
}
if (startIndexInclusive < 0) {
startIndexInclusive = 0;
}
if (endIndexExclusive > array.length) {
endIndexExclusive = array.length;
}
int newSize = endIndexExclusive - startIndexInclusive;
if (newSize <= 0) {
return new long[0];
}
long[] subarray = new long[newSize];
System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
return subarray;
}
}
Produces a new short array containing the elements between the start and end indices.
import java.lang.reflect.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.
*
*
*/
/**
* @author Stephen Colebourne
* @author Moritz Petersen
* @author
* @author Maarten Coene
* @since 2.0
* @version $Id: ArrayUtils.java 632503 2008-03-01 00:21:52Z ggregory $
*/
public class Main {
/**
* <p>Produces a new <code>short</code> array containing the elements
* between the start and end indices.</p>
*
* <p>The start index is inclusive, the end index exclusive.
* Null array input produces null output.</p>
*
* @param array the array
* @param startIndexInclusive the starting index. Undervalue (<0)
* is promoted to 0, overvalue (>array.length) results
* in an empty array.
* @param endIndexExclusive elements up to endIndex-1 are present in the
* returned subarray. Undervalue (< startIndex) produces
* empty array, overvalue (>array.length) is demoted to
* array length.
* @return a new array containing the elements between
* the start and end indices.
* @since 2.1
*/
public static short[] subarray(short[] array, int startIndexInclusive, int endIndexExclusive) {
if (array == null) {
return null;
}
if (startIndexInclusive < 0) {
startIndexInclusive = 0;
}
if (endIndexExclusive > array.length) {
endIndexExclusive = array.length;
}
int newSize = endIndexExclusive - startIndexInclusive;
if (newSize <= 0) {
return new short[0];
}
short[] subarray = new short[newSize];
System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
return subarray;
}
}
Quicksort implementation for sorting arrays
/*
* Copyright (c) 1998 - 2005 Versant Corporation
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Versant Corporation - initial API and implementation
*/
import java.util.ruparator;
/**
* Quicksort implementation for sorting arrays. Unlike the merge sort in
* java.utils.Collections this one does not create any objects. There are
* two implementations, one for arrays of Comparable"s and another that
* uses a comparator.
*/
public class Quicksort {
private Quicksort() {
}
/**
* Sort the first size entries in a.
*/
public static void quicksort(Object[] a, int size) {
quicksort(a, 0, size - 1);
}
/**
* Sort the entries in a between left and right inclusive.
*/
public static void quicksort(Object[] a, int left, int right) {
int size = right - left + 1;
switch (size) {
case 0:
case 1:
break;
case 2:
if (compare(a[left], a[right]) > 0) swap(a, left, right);
break;
case 3:
if (compare(a[left], a[right - 1]) > 0) swap(a, left, right - 1);
if (compare(a[left], a[right]) > 0) swap(a, left, right);
if (compare(a[left + 1], a[right]) > 0) swap(a, left + 1, right);
break;
default:
int median = median(a, left, right);
int partition = partition(a, left, right, median);
quicksort(a, left, partition - 1);
quicksort(a, partition + 1, right);
}
}
private static int compare(Object a, Object b) {
if (a == null) {
return b == null ? 0 : -1;
} else if (b == null) {
return +1;
} else {
return ((Comparable)a).rupareTo(b);
}
}
private static void swap(Object[] a, int left, int right) {
Object t = a[left];
a[left] = a[right];
a[right] = t;
}
private static int median(Object[] a, int left, int right) {
int center = (left + right) / 2;
if (compare(a[left], a[center]) > 0) swap(a, left, center);
if (compare(a[left], a[right]) > 0) swap(a, left, right);
if (compare(a[center], a[right]) > 0) swap(a, center, right);
swap(a, center, right - 1);
return right - 1;
}
private static int partition(Object[] a, int left, int right, int pivotIndex) {
int leftIndex = left;
int rightIndex = right - 1;
while (true) {
while (compare(a[++leftIndex], a[pivotIndex]) < 0);
while (compare(a[--rightIndex], a[pivotIndex]) > 0);
if (leftIndex >= rightIndex) {
break; // pointers cross so partition done
} else {
swap(a, leftIndex, rightIndex);
}
}
swap(a, leftIndex, right - 1); // restore pivot
return leftIndex; // return pivot location
}
/**
* Sort the first size entries in a.
*/
public static void quicksort(Object[] a, int size, Comparator c) {
quicksort(a, 0, size - 1, c);
}
/**
* Sort the entries in a between left and right inclusive.
*/
public static void quicksort(Object[] a, int left, int right, Comparator c) {
int size = right - left + 1;
switch (size) {
case 0:
case 1:
break;
case 2:
if (c.rupare(a[left], a[right]) > 0) swap(a, left, right);
break;
case 3:
if (c.rupare(a[left], a[right - 1]) > 0) swap(a, left, right - 1);
if (c.rupare(a[left], a[right]) > 0) swap(a, left, right);
if (c.rupare(a[left + 1], a[right]) > 0) swap(a, left + 1, right);
break;
default:
int median = median(a, left, right, c);
int partition = partition(a, left, right, median, c);
quicksort(a, left, partition - 1, c);
quicksort(a, partition + 1, right, c);
}
}
private static int median(Object[] a, int left, int right, Comparator c) {
int center = (left + right) / 2;
if (c.rupare(a[left], a[center]) > 0) swap(a, left, center);
if (c.rupare(a[left], a[right]) > 0) swap(a, left, right);
if (c.rupare(a[center], a[right]) > 0) swap(a, center, right);
swap(a, center, right - 1);
return right - 1;
}
private static int partition(Object[] a, int left, int right,
int pivotIndex, Comparator c) {
int leftIndex = left;
int rightIndex = right - 1;
while (true) {
while (c.rupare(a[++leftIndex], a[pivotIndex]) < 0);
while (c.rupare(a[--rightIndex], a[pivotIndex]) > 0);
if (leftIndex >= rightIndex) {
break; // pointers cross so partition done
} else {
swap(a, leftIndex, rightIndex);
}
}
swap(a, leftIndex, right - 1); // restore pivot
return leftIndex; // return pivot location
}
}
Returns the index in the source array where the first occurrence of the specified byte pattern is found
/**********************************************************************************
*
* Copyright (c) 2003, 2004 The Regents of the University of Michigan, Trustees of Indiana University,
* Board of Trustees of the Leland Stanford, Jr., University, and The MIT Corporation
*
* Licensed under the Educational Community License Version 1.0 (the "License");
* By obtaining, using and/or copying this Original Work, you agree that you have read,
* understand, and will comply with the terms and conditions of the Educational Community License.
* You may obtain a copy of the License at:
*
* http://cvs.sakaiproject.org/licenses/license_1_0.html
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
**********************************************************************************/
/**
* Byte utilities
*/
public class ByteUtils {
/**
* Returns the index in the source array where the first occurrence of the
* specified byte pattern is found
*
* @param source
* Byte array to examine
* @param match
* Byte array to locate in <code>source</code>
* @return Index of the first matching character (-1 if no match)
*/
public static int indexOf(byte[] source, byte[] match) {
for (int i = 0; i < source.length; i++) {
if (startsWith(source, i, match)) {
return i;
}
}
return -1;
}
/**
* Returns the index in the source array where the last occurrence of the
* specified text (a String, converted to a byte array) is found
*
* @param source
* Byte array to examine
* @param matchString
* String to locate in <code>source</code>
* @return Index of the first matching character (-1 if no match)
*/
public static int lastIndexOf(byte[] source, String matchString) {
return lastIndexOf(source, matchString.getBytes());
}
/**
* Returns the index in the source array where the last occurrence of the
* specified byte pattern is found
*
* @param source
* Byte array to examine
* @param match
* Byte array to locate in <code>source</code>
* @return Index of the last matching character (-1 if no match)
*/
public static int lastIndexOf(byte[] source, byte[] match) {
if (source.length < match.length) {
return -1;
}
for (int i = (source.length - match.length); i >= 0; i--) {
if (startsWith(source, i, match)) {
return i;
}
}
return -1;
}
/**
* Does this byte array begin with match array content?
*
* @param source
* Byte array to examine
* @param match
* Byte array to locate in <code>source</code>
* @return true If the starting bytes are equal
*/
public static boolean startsWith(byte[] source, byte[] match) {
return startsWith(source, 0, match);
}
/**
* Does this byte array begin with match array content?
*
* @param source
* Byte array to examine
* @param offset
* An offset into the <code>source</code> array
* @param match
* Byte array to locate in <code>source</code>
* @return true If the starting bytes are equal
*/
public static boolean startsWith(byte[] source, int offset, byte[] match) {
if (match.length > (source.length - offset)) {
return false;
}
for (int i = 0; i < match.length; i++) {
if (source[offset + i] != match[i]) {
return false;
}
}
return true;
}
/**
* Does the source array equal the match array?
*
* @param source
* Byte array to examine
* @param offset
* An offset into the <code>source</code> array
* @param match
* Byte array to locate in <code>source</code>
* @return true If the two arrays are equal
*/
public static boolean equals(byte[] source, byte[] match) {
if (match.length != source.length) {
return false;
}
return startsWith(source, 0, match);
}
/**
* Copies bytes from the source byte array to the destination array
*
* @param source
* The source array
* @param srcBegin
* Index of the first source byte to copy
* @param srcEnd
* Index after the last source byte to copy
* @param destination
* The destination array
* @param dstBegin
* The starting offset in the destination array
*/
public static void getBytes(byte[] source, int srcBegin, int srcEnd, byte[] destination,
int dstBegin) {
System.arraycopy(source, srcBegin, destination, dstBegin, srcEnd - srcBegin);
}
/**
* Return a new byte array containing a sub-portion of the source array
*
* @param srcBegin
* The beginning index (inclusive)
* @param srcEnd
* The ending index (exclusive)
* @return The new, populated byte array
*/
public static byte[] subbytes(byte[] source, int srcBegin, int srcEnd) {
byte destination[];
destination = new byte[srcEnd - srcBegin];
getBytes(source, srcBegin, srcEnd, destination, 0);
return destination;
}
/**
* Return a new byte array containing a sub-portion of the source array
*
* @param srcBegin
* The beginning index (inclusive)
* @return The new, populated byte array
*/
public static byte[] subbytes(byte[] source, int srcBegin) {
return subbytes(source, srcBegin, source.length);
}
}
Returns the index in the source array where the first occurrence of the specified text (a String, converted to a byte array) is found
/**********************************************************************************
*
* Copyright (c) 2003, 2004 The Regents of the University of Michigan, Trustees of Indiana University,
* Board of Trustees of the Leland Stanford, Jr., University, and The MIT Corporation
*
* Licensed under the Educational Community License Version 1.0 (the "License");
* By obtaining, using and/or copying this Original Work, you agree that you have read,
* understand, and will comply with the terms and conditions of the Educational Community License.
* You may obtain a copy of the License at:
*
* http://cvs.sakaiproject.org/licenses/license_1_0.html
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
**********************************************************************************/
/**
* Byte utilities
*/
public class ByteUtils {
/**
* Returns the index in the source array where the first occurrence of the
* specified text (a String, converted to a byte array) is found
*
* @param source
* Byte array to examine
* @param matchString
* String to locate in <code>source</code>
* @return Index of the first matching character (-1 if no match)
*/
public static int indexOf(byte[] source, String matchString) {
return indexOf(source, matchString.getBytes());
}
/**
* Returns the index in the source array where the first occurrence of the
* specified byte pattern is found
*
* @param source
* Byte array to examine
* @param match
* Byte array to locate in <code>source</code>
* @return Index of the first matching character (-1 if no match)
*/
public static int indexOf(byte[] source, byte[] match) {
for (int i = 0; i < source.length; i++) {
if (startsWith(source, i, match)) {
return i;
}
}
return -1;
}
/**
* Returns the index in the source array where the last occurrence of the
* specified text (a String, converted to a byte array) is found
*
* @param source
* Byte array to examine
* @param matchString
* String to locate in <code>source</code>
* @return Index of the first matching character (-1 if no match)
*/
public static int lastIndexOf(byte[] source, String matchString) {
return lastIndexOf(source, matchString.getBytes());
}
/**
* Returns the index in the source array where the last occurrence of the
* specified byte pattern is found
*
* @param source
* Byte array to examine
* @param match
* Byte array to locate in <code>source</code>
* @return Index of the last matching character (-1 if no match)
*/
public static int lastIndexOf(byte[] source, byte[] match) {
if (source.length < match.length) {
return -1;
}
for (int i = (source.length - match.length); i >= 0; i--) {
if (startsWith(source, i, match)) {
return i;
}
}
return -1;
}
/**
* Does this byte array begin with match array content?
*
* @param source
* Byte array to examine
* @param match
* Byte array to locate in <code>source</code>
* @return true If the starting bytes are equal
*/
public static boolean startsWith(byte[] source, byte[] match) {
return startsWith(source, 0, match);
}
/**
* Does this byte array begin with match array content?
*
* @param source
* Byte array to examine
* @param offset
* An offset into the <code>source</code> array
* @param match
* Byte array to locate in <code>source</code>
* @return true If the starting bytes are equal
*/
public static boolean startsWith(byte[] source, int offset, byte[] match) {
if (match.length > (source.length - offset)) {
return false;
}
for (int i = 0; i < match.length; i++) {
if (source[offset + i] != match[i]) {
return false;
}
}
return true;
}
/**
* Does the source array equal the match array?
*
* @param source
* Byte array to examine
* @param offset
* An offset into the <code>source</code> array
* @param match
* Byte array to locate in <code>source</code>
* @return true If the two arrays are equal
*/
public static boolean equals(byte[] source, byte[] match) {
if (match.length != source.length) {
return false;
}
return startsWith(source, 0, match);
}
/**
* Copies bytes from the source byte array to the destination array
*
* @param source
* The source array
* @param srcBegin
* Index of the first source byte to copy
* @param srcEnd
* Index after the last source byte to copy
* @param destination
* The destination array
* @param dstBegin
* The starting offset in the destination array
*/
public static void getBytes(byte[] source, int srcBegin, int srcEnd, byte[] destination,
int dstBegin) {
System.arraycopy(source, srcBegin, destination, dstBegin, srcEnd - srcBegin);
}
/**
* Return a new byte array containing a sub-portion of the source array
*
* @param srcBegin
* The beginning index (inclusive)
* @param srcEnd
* The ending index (exclusive)
* @return The new, populated byte array
*/
public static byte[] subbytes(byte[] source, int srcBegin, int srcEnd) {
byte destination[];
destination = new byte[srcEnd - srcBegin];
getBytes(source, srcBegin, srcEnd, destination, 0);
return destination;
}
/**
* Return a new byte array containing a sub-portion of the source array
*
* @param srcBegin
* The beginning index (inclusive)
* @return The new, populated byte array
*/
public static byte[] subbytes(byte[] source, int srcBegin) {
return subbytes(source, srcBegin, source.length);
}
/*
* Test
*/
public static void main(String[] args) throws Exception {
byte byteText[];
int index, last;
byteText = "XXXXXXXXXX".getBytes();
index = indexOf(byteText, "XXX");
last = lastIndexOf(byteText, "XXX");
}
}
Returns the index in the source array where the last occurrence of the specified byte pattern is found
/**********************************************************************************
*
* Copyright (c) 2003, 2004 The Regents of the University of Michigan, Trustees of Indiana University,
* Board of Trustees of the Leland Stanford, Jr., University, and The MIT Corporation
*
* Licensed under the Educational Community License Version 1.0 (the "License");
* By obtaining, using and/or copying this Original Work, you agree that you have read,
* understand, and will comply with the terms and conditions of the Educational Community License.
* You may obtain a copy of the License at:
*
* http://cvs.sakaiproject.org/licenses/license_1_0.html
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
**********************************************************************************/
/**
* Byte utilities
*/
public class ByteUtils {
/**
* Returns the index in the source array where the last occurrence of the
* specified byte pattern is found
*
* @param source
* Byte array to examine
* @param match
* Byte array to locate in <code>source</code>
* @return Index of the last matching character (-1 if no match)
*/
public static int lastIndexOf(byte[] source, byte[] match) {
if (source.length < match.length) {
return -1;
}
for (int i = (source.length - match.length); i >= 0; i--) {
if (startsWith(source, i, match)) {
return i;
}
}
return -1;
}
/**
* Does this byte array begin with match array content?
*
* @param source
* Byte array to examine
* @param match
* Byte array to locate in <code>source</code>
* @return true If the starting bytes are equal
*/
public static boolean startsWith(byte[] source, byte[] match) {
return startsWith(source, 0, match);
}
/**
* Does this byte array begin with match array content?
*
* @param source
* Byte array to examine
* @param offset
* An offset into the <code>source</code> array
* @param match
* Byte array to locate in <code>source</code>
* @return true If the starting bytes are equal
*/
public static boolean startsWith(byte[] source, int offset, byte[] match) {
if (match.length > (source.length - offset)) {
return false;
}
for (int i = 0; i < match.length; i++) {
if (source[offset + i] != match[i]) {
return false;
}
}
return true;
}
/**
* Does the source array equal the match array?
*
* @param source
* Byte array to examine
* @param offset
* An offset into the <code>source</code> array
* @param match
* Byte array to locate in <code>source</code>
* @return true If the two arrays are equal
*/
public static boolean equals(byte[] source, byte[] match) {
if (match.length != source.length) {
return false;
}
return startsWith(source, 0, match);
}
/**
* Copies bytes from the source byte array to the destination array
*
* @param source
* The source array
* @param srcBegin
* Index of the first source byte to copy
* @param srcEnd
* Index after the last source byte to copy
* @param destination
* The destination array
* @param dstBegin
* The starting offset in the destination array
*/
public static void getBytes(byte[] source, int srcBegin, int srcEnd, byte[] destination,
int dstBegin) {
System.arraycopy(source, srcBegin, destination, dstBegin, srcEnd - srcBegin);
}
/**
* Return a new byte array containing a sub-portion of the source array
*
* @param srcBegin
* The beginning index (inclusive)
* @param srcEnd
* The ending index (exclusive)
* @return The new, populated byte array
*/
public static byte[] subbytes(byte[] source, int srcBegin, int srcEnd) {
byte destination[];
destination = new byte[srcEnd - srcBegin];
getBytes(source, srcBegin, srcEnd, destination, 0);
return destination;
}
/**
* Return a new byte array containing a sub-portion of the source array
*
* @param srcBegin
* The beginning index (inclusive)
* @return The new, populated byte array
*/
public static byte[] subbytes(byte[] source, int srcBegin) {
return subbytes(source, srcBegin, source.length);
}
}
Returns the index in the source array where the last occurrence of the specified text (a String, converted to a byte array) is found
/**********************************************************************************
*
* Copyright (c) 2003, 2004 The Regents of the University of Michigan, Trustees of Indiana University,
* Board of Trustees of the Leland Stanford, Jr., University, and The MIT Corporation
*
* Licensed under the Educational Community License Version 1.0 (the "License");
* By obtaining, using and/or copying this Original Work, you agree that you have read,
* understand, and will comply with the terms and conditions of the Educational Community License.
* You may obtain a copy of the License at:
*
* http://cvs.sakaiproject.org/licenses/license_1_0.html
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
**********************************************************************************/
/**
* Byte utilities
*/
public class ByteUtils {
/**
* Returns the index in the source array where the last occurrence of the
* specified text (a String, converted to a byte array) is found
*
* @param source
* Byte array to examine
* @param matchString
* String to locate in <code>source</code>
* @return Index of the first matching character (-1 if no match)
*/
public static int lastIndexOf(byte[] source, String matchString) {
return lastIndexOf(source, matchString.getBytes());
}
/**
* Returns the index in the source array where the last occurrence of the
* specified byte pattern is found
*
* @param source
* Byte array to examine
* @param match
* Byte array to locate in <code>source</code>
* @return Index of the last matching character (-1 if no match)
*/
public static int lastIndexOf(byte[] source, byte[] match) {
if (source.length < match.length) {
return -1;
}
for (int i = (source.length - match.length); i >= 0; i--) {
if (startsWith(source, i, match)) {
return i;
}
}
return -1;
}
/**
* Does this byte array begin with match array content?
*
* @param source
* Byte array to examine
* @param match
* Byte array to locate in <code>source</code>
* @return true If the starting bytes are equal
*/
public static boolean startsWith(byte[] source, byte[] match) {
return startsWith(source, 0, match);
}
/**
* Does this byte array begin with match array content?
*
* @param source
* Byte array to examine
* @param offset
* An offset into the <code>source</code> array
* @param match
* Byte array to locate in <code>source</code>
* @return true If the starting bytes are equal
*/
public static boolean startsWith(byte[] source, int offset, byte[] match) {
if (match.length > (source.length - offset)) {
return false;
}
for (int i = 0; i < match.length; i++) {
if (source[offset + i] != match[i]) {
return false;
}
}
return true;
}
/**
* Does the source array equal the match array?
*
* @param source
* Byte array to examine
* @param offset
* An offset into the <code>source</code> array
* @param match
* Byte array to locate in <code>source</code>
* @return true If the two arrays are equal
*/
public static boolean equals(byte[] source, byte[] match) {
if (match.length != source.length) {
return false;
}
return startsWith(source, 0, match);
}
/**
* Copies bytes from the source byte array to the destination array
*
* @param source
* The source array
* @param srcBegin
* Index of the first source byte to copy
* @param srcEnd
* Index after the last source byte to copy
* @param destination
* The destination array
* @param dstBegin
* The starting offset in the destination array
*/
public static void getBytes(byte[] source, int srcBegin, int srcEnd, byte[] destination,
int dstBegin) {
System.arraycopy(source, srcBegin, destination, dstBegin, srcEnd - srcBegin);
}
/**
* Return a new byte array containing a sub-portion of the source array
*
* @param srcBegin
* The beginning index (inclusive)
* @param srcEnd
* The ending index (exclusive)
* @return The new, populated byte array
*/
public static byte[] subbytes(byte[] source, int srcBegin, int srcEnd) {
byte destination[];
destination = new byte[srcEnd - srcBegin];
getBytes(source, srcBegin, srcEnd, destination, 0);
return destination;
}
/**
* Return a new byte array containing a sub-portion of the source array
*
* @param srcBegin
* The beginning index (inclusive)
* @return The new, populated byte array
*/
public static byte[] subbytes(byte[] source, int srcBegin) {
return subbytes(source, srcBegin, source.length);
}
}
Returns the maximum value in a byte-type 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.
*/
/**
* <p>Provides extra functionality for Java Number classes.</p>
*
* @author
* @since 2.0
* @version $Id: NumberUtils.java 609475 2008-01-06 23:58:59Z bayard $
*/
public class Main {
/**
* <p>Returns the maximum value in an array.</p>
*
* @param array an array, must not be null or empty
* @return the minimum value in the array
* @throws IllegalArgumentException if <code>array</code> is <code>null</code>
* @throws IllegalArgumentException if <code>array</code> is empty
*/
public static byte max(byte[] array) {
// Validates input
if (array == null) {
throw new IllegalArgumentException("The Array must not be null");
} else if (array.length == 0) {
throw new IllegalArgumentException("Array cannot be empty.");
}
// Finds and returns max
byte max = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
}
}
return max;
}
}
Returns the maximum value in a double-type 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.
*/
/**
* <p>Provides extra functionality for Java Number classes.</p>
*
* @author
* @since 2.0
* @version $Id: NumberUtils.java 609475 2008-01-06 23:58:59Z bayard $
*/
public class Main {
/**
* <p>Returns the maximum value in an array.</p>
*
* @param array an array, must not be null or empty
* @return the minimum value in the array
* @throws IllegalArgumentException if <code>array</code> is <code>null</code>
* @throws IllegalArgumentException if <code>array</code> is empty
* @see IEEE754rUtils#max(double[]) IEEE754rUtils for a version of this method that handles NaN differently
*/
public static double max(double[] array) {
// Validates input
if (array== null) {
throw new IllegalArgumentException("The Array must not be null");
} else if (array.length == 0) {
throw new IllegalArgumentException("Array cannot be empty.");
}
// Finds and returns max
double max = array[0];
for (int j = 1; j < array.length; j++) {
if (Double.isNaN(array[j])) {
return Double.NaN;
}
if (array[j] > max) {
max = array[j];
}
}
return max;
}
}
Returns the maximum value in a float-type 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.
*/
/**
* <p>Provides extra functionality for Java Number classes.</p>
*
* @author
* @since 2.0
* @version $Id: NumberUtils.java 609475 2008-01-06 23:58:59Z bayard $
*/
public class Main {
/**
* <p>Returns the maximum value in an array.</p>
*
* @param array an array, must not be null or empty
* @return the minimum value in the array
* @throws IllegalArgumentException if <code>array</code> is <code>null</code>
* @throws IllegalArgumentException if <code>array</code> is empty
* @see IEEE754rUtils#max(float[]) IEEE754rUtils for a version of this method that handles NaN differently
*/
public static float max(float[] array) {
// Validates input
if (array == null) {
throw new IllegalArgumentException("The Array must not be null");
} else if (array.length == 0) {
throw new IllegalArgumentException("Array cannot be empty.");
}
// Finds and returns max
float max = array[0];
for (int j = 1; j < array.length; j++) {
if (Float.isNaN(array[j])) {
return Float.NaN;
}
if (array[j] > max) {
max = array[j];
}
}
return max;
}
}
Returns the maximum value in a long-value 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.
*/
/**
* <p>Provides extra functionality for Java Number classes.</p>
*
* @author
* @since 2.0
* @version $Id: NumberUtils.java 609475 2008-01-06 23:58:59Z bayard $
*/
public class Main {
/**
* <p>Returns the maximum value in an array.</p>
*
* @param array an array, must not be null or empty
* @return the minimum value in the array
* @throws IllegalArgumentException if <code>array</code> is <code>null</code>
* @throws IllegalArgumentException if <code>array</code> is empty
*/
public static long max(long[] array) {
// Validates input
if (array == null) {
throw new IllegalArgumentException("The Array must not be null");
} else if (array.length == 0) {
throw new IllegalArgumentException("Array cannot be empty.");
}
// Finds and returns max
long max = array[0];
for (int j = 1; j < array.length; j++) {
if (array[j] > max) {
max = array[j];
}
}
return max;
}
}
Returns the maximum value in an int-type 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.
*/
/**
* <p>Provides extra functionality for Java Number classes.</p>
*
* @author
* @since 2.0
* @version $Id: NumberUtils.java 609475 2008-01-06 23:58:59Z bayard $
*/
public class Main {
/**
* <p>Returns the maximum value in an array.</p>
*
* @param array an array, must not be null or empty
* @return the minimum value in the array
* @throws IllegalArgumentException if <code>array</code> is <code>null</code>
* @throws IllegalArgumentException if <code>array</code> is empty
*/
public static int max(int[] array) {
// Validates input
if (array == null) {
throw new IllegalArgumentException("The Array must not be null");
} else if (array.length == 0) {
throw new IllegalArgumentException("Array cannot be empty.");
}
// Finds and returns max
int max = array[0];
for (int j = 1; j < array.length; j++) {
if (array[j] > max) {
max = array[j];
}
}
return max;
}
}
Returns the maximum value in a short-type 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.
*/
/**
* <p>Provides extra functionality for Java Number classes.</p>
*
* @author
* @since 2.0
* @version $Id: NumberUtils.java 609475 2008-01-06 23:58:59Z bayard $
*/
public class Main {
/**
* <p>Returns the maximum value in an array.</p>
*
* @param array an array, must not be null or empty
* @return the minimum value in the array
* @throws IllegalArgumentException if <code>array</code> is <code>null</code>
* @throws IllegalArgumentException if <code>array</code> is empty
*/
public static short max(short[] array) {
// Validates input
if (array == null) {
throw new IllegalArgumentException("The Array must not be null");
} else if (array.length == 0) {
throw new IllegalArgumentException("Array cannot be empty.");
}
// Finds and returns max
short max = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
}
}
return max;
}
}
Returns the minimum value in a double-type 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.
*/
/**
* <p>Provides extra functionality for Java Number classes.</p>
*
* @author
* @since 2.0
* @version $Id: NumberUtils.java 609475 2008-01-06 23:58:59Z bayard $
*/
public class Main {
/**
* <p>Returns the minimum value in an array.</p>
*
* @param array an array, must not be null or empty
* @return the minimum value in the array
* @throws IllegalArgumentException if <code>array</code> is <code>null</code>
* @throws IllegalArgumentException if <code>array</code> is empty
* @see IEEE754rUtils#min(double[]) IEEE754rUtils for a version of this method that handles NaN differently
*/
public static double min(double[] array) {
// Validates input
if (array == null) {
throw new IllegalArgumentException("The Array must not be null");
} else if (array.length == 0) {
throw new IllegalArgumentException("Array cannot be empty.");
}
// Finds and returns min
double min = array[0];
for (int i = 1; i < array.length; i++) {
if (Double.isNaN(array[i])) {
return Double.NaN;
}
if (array[i] < min) {
min = array[i];
}
}
return min;
}
}
Returns the minimum value in a float-value 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.
*/
/**
* <p>Provides extra functionality for Java Number classes.</p>
*
* @author
* @since 2.0
* @version $Id: NumberUtils.java 609475 2008-01-06 23:58:59Z bayard $
*/
public class Main {
/**
* <p>Returns the minimum value in an array.</p>
*
* @param array an array, must not be null or empty
* @return the minimum value in the array
* @throws IllegalArgumentException if <code>array</code> is <code>null</code>
* @throws IllegalArgumentException if <code>array</code> is empty
* @see IEEE754rUtils#min(float[]) IEEE754rUtils for a version of this method that handles NaN differently
*/
public static float min(float[] array) {
// Validates input
if (array == null) {
throw new IllegalArgumentException("The Array must not be null");
} else if (array.length == 0) {
throw new IllegalArgumentException("Array cannot be empty.");
}
// Finds and returns min
float min = array[0];
for (int i = 1; i < array.length; i++) {
if (Float.isNaN(array[i])) {
return Float.NaN;
}
if (array[i] < min) {
min = array[i];
}
}
return min;
}
}
Returns the minimum value in an 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.
*/
/**
* <p>Provides extra functionality for Java Number classes.</p>
*
* @author
* @since 2.0
* @version $Id: NumberUtils.java 609475 2008-01-06 23:58:59Z bayard $
*/
public class Main {
/**
* <p>Returns the minimum value in an array.</p>
*
* @param array an array, must not be null or empty
* @return the minimum value in the array
* @throws IllegalArgumentException if <code>array</code> is <code>null</code>
* @throws IllegalArgumentException if <code>array</code> is empty
*/
public static long min(long[] array) {
// Validates input
if (array == null) {
throw new IllegalArgumentException("The Array must not be null");
} else if (array.length == 0) {
throw new IllegalArgumentException("Array cannot be empty.");
}
// Finds and returns min
long min = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] < min) {
min = array[i];
}
}
return min;
}
}
Returns the minimum value in an int-type 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.
*/
/**
* <p>Provides extra functionality for Java Number classes.</p>
*
* @author
* @since 2.0
* @version $Id: NumberUtils.java 609475 2008-01-06 23:58:59Z bayard $
*/
public class Main {
/**
* <p>Returns the minimum value in an array.</p>
*
* @param array an array, must not be null or empty
* @return the minimum value in the array
* @throws IllegalArgumentException if <code>array</code> is <code>null</code>
* @throws IllegalArgumentException if <code>array</code> is empty
*/
public static int min(int[] array) {
// Validates input
if (array == null) {
throw new IllegalArgumentException("The Array must not be null");
} else if (array.length == 0) {
throw new IllegalArgumentException("Array cannot be empty.");
}
// Finds and returns min
int min = array[0];
for (int j = 1; j < array.length; j++) {
if (array[j] < min) {
min = array[j];
}
}
return min;
}
}
Returns the minimum value in an short-type 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.
*/
/**
* <p>Provides extra functionality for Java Number classes.</p>
*
* @author
* @since 2.0
* @version $Id: NumberUtils.java 609475 2008-01-06 23:58:59Z bayard $
*/
public class Main {
/**
* <p>Returns the minimum value in an array.</p>
*
* @param array an array, must not be null or empty
* @return the minimum value in the array
* @throws IllegalArgumentException if <code>array</code> is <code>null</code>
* @throws IllegalArgumentException if <code>array</code> is empty
*/
public static short min(short[] array) {
// Validates input
if (array == null) {
throw new IllegalArgumentException("The Array must not be null");
} else if (array.length == 0) {
throw new IllegalArgumentException("Array cannot be empty.");
}
// Finds and returns min
short min = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] < min) {
min = array[i];
}
}
return min;
}
}
Returns the minimum value in a short-type 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.
*/
/**
* <p>Provides extra functionality for Java Number classes.</p>
*
* @author
* @since 2.0
* @version $Id: NumberUtils.java 609475 2008-01-06 23:58:59Z bayard $
*/
public class Main {
/**
* <p>Returns the minimum value in an array.</p>
*
* @param array an array, must not be null or empty
* @return the minimum value in the array
* @throws IllegalArgumentException if <code>array</code> is <code>null</code>
* @throws IllegalArgumentException if <code>array</code> is empty
*/
public static byte min(byte[] array) {
// Validates input
if (array == null) {
throw new IllegalArgumentException("The Array must not be null");
} else if (array.length == 0) {
throw new IllegalArgumentException("Array cannot be empty.");
}
// Finds and returns min
byte min = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] < min) {
min = array[i];
}
}
return min;
}
}
Reverses the order of the given boolean type value 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.
*
*
*/
/**
* @author Stephen Colebourne
* @author Moritz Petersen
* @author
* @author Maarten Coene
* @since 2.0
* @version $Id: ArrayUtils.java 632503 2008-03-01 00:21:52Z ggregory $
*/
public class Main {
/**
* <p>Reverses the order of the given array.</p>
*
* <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(boolean[] array) {
if (array == null) {
return;
}
int i = 0;
int j = array.length - 1;
boolean tmp;
while (j > i) {
tmp = array[j];
array[j] = array[i];
array[i] = tmp;
j--;
i++;
}
}
}
Reverses the order of the given byte type 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.
*
*
*/
/**
* @author Stephen Colebourne
* @author Moritz Petersen
* @author
* @author Maarten Coene
* @since 2.0
* @version $Id: ArrayUtils.java 632503 2008-03-01 00:21:52Z ggregory $
*/
public class Main {
/**
* <p>Reverses the order of the given array.</p>
*
* <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(byte[] array) {
if (array == null) {
return;
}
int i = 0;
int j = array.length - 1;
byte tmp;
while (j > i) {
tmp = array[j];
array[j] = array[i];
array[i] = tmp;
j--;
i++;
}
}
}
Reverses the order of the given char type value 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.
*
*
*/
/**
* @author Stephen Colebourne
* @author Moritz Petersen
* @author
* @author Maarten Coene
* @since 2.0
* @version $Id: ArrayUtils.java 632503 2008-03-01 00:21:52Z ggregory $
*/
public class Main {
/**
* <p>Reverses the order of the given array.</p>
*
* <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(char[] array) {
if (array == null) {
return;
}
int i = 0;
int j = array.length - 1;
char tmp;
while (j > i) {
tmp = array[j];
array[j] = array[i];
array[i] = tmp;
j--;
i++;
}
}
}
Reverses the order of the given double value type 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.
*
*
*/
/**
* @author Stephen Colebourne
* @author Moritz Petersen
* @author
* @author Maarten Coene
* @since 2.0
* @version $Id: ArrayUtils.java 632503 2008-03-01 00:21:52Z ggregory $
*/
public class Main {
/**
* <p>Reverses the order of the given array.</p>
*
* <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(double[] array) {
if (array == null) {
return;
}
int i = 0;
int j = array.length - 1;
double tmp;
while (j > i) {
tmp = array[j];
array[j] = array[i];
array[i] = tmp;
j--;
i++;
}
}
}
Reverses the order of the given float type value 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.
*
*
*/
/**
* @author Stephen Colebourne
* @author Moritz Petersen
* @author
* @author Maarten Coene
* @since 2.0
* @version $Id: ArrayUtils.java 632503 2008-03-01 00:21:52Z ggregory $
*/
public class Main {
/**
* <p>Reverses the order of the given array.</p>
*
* <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(float[] array) {
if (array == null) {
return;
}
int i = 0;
int j = array.length - 1;
float tmp;
while (j > i) {
tmp = array[j];
array[j] = array[i];
array[i] = tmp;
j--;
i++;
}
}
}
Reverses the order of the given int type value 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.
*
*
*/
/**
* @author Stephen Colebourne
* @author Moritz Petersen
* @author
* @author Maarten Coene
* @since 2.0
* @version $Id: ArrayUtils.java 632503 2008-03-01 00:21:52Z ggregory $
*/
public class Main {
/**
* <p>Reverses the order of the given array.</p>
*
* <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(int[] array) {
if (array == null) {
return;
}
int i = 0;
int j = array.length - 1;
int tmp;
while (j > i) {
tmp = array[j];
array[j] = array[i];
array[i] = tmp;
j--;
i++;
}
}
}
Reverses the order of the given long type value 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.
*
*
*/
/**
* @author Stephen Colebourne
* @author Moritz Petersen
* @author
* @author Maarten Coene
* @since 2.0
* @version $Id: ArrayUtils.java 632503 2008-03-01 00:21:52Z ggregory $
*/
public class Main {
/**
* <p>Reverses the order of the given array.</p>
*
* <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(long[] array) {
if (array == null) {
return;
}
int i = 0;
int j = array.length - 1;
long tmp;
while (j > i) {
tmp = array[j];
array[j] = array[i];
array[i] = tmp;
j--;
i++;
}
}
}
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 {
/**
* <p>Reverses the order of the given array.</p>
*
* <p>There is no special handling for multi-dimensional arrays.</p>
*
* <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++;
}
}
}
Reverses the order of the given short type value 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.
*
*
*/
/**
* @author Stephen Colebourne
* @author Moritz Petersen
* @author
* @author Maarten Coene
* @since 2.0
* @version $Id: ArrayUtils.java 632503 2008-03-01 00:21:52Z ggregory $
*/
public class Main {
/**
* <p>Reverses the order of the given array.</p>
*
* <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(short[] array) {
if (array == null) {
return;
}
int i = 0;
int j = array.length - 1;
short tmp;
while (j > i) {
tmp = array[j];
array[j] = array[i];
array[i] = tmp;
j--;
i++;
}
}
}
Search for an object in an array.
/**********************************************************************************
* $URL: https://source.sakaiproject.org/svn/util/branches/sakai_2-5-4/util-util/util/src/java/org/sakaiproject/util/ArrayUtil.java $
* $Id: ArrayUtil.java 7914 2006-04-18 18:11:25Z ggolden@umich.edu $
***********************************************************************************
*
* Copyright (c) 2006 The Sakai Foundation.
*
* Licensed under the Educational Community License, Version 1.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.opensource.org/licenses/ecl1.php
*
* 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.
*
**********************************************************************************/
/**
* <p>
* ArrayUtil collects together some Array utility methods.
* </p>
*/
public class ArrayUtil
{
/**
* Search for an object in an array.
*
* @param target
* The target array
* @param search
* The object to search for.
* @return true if search is "in" (equal to any object in) the target, false if not
*/
public static boolean contains(Object[] target, Object search)
{
if ((target == null) || (search == null)) return false;
if (target.length == 0) return false;
try
{
for (int i = 0; i < target.length; i++)
{
if (search.equals(target[i])) return true;
}
}
catch (Throwable e)
{
return false;
}
return false;
}
}
Search for a specified value of an array
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int items[] = { 5, 4, 6, 1, 8, 9, 6, 7, 3, 2 };
Arrays.sort(items);
int index = Arrays.binarySearch(items, 1);
System.out.println("Search item found at: " + index);
}
}
Sort array utilities
/*
* Copyright 2004, 2005, 2006 Odysseus Software GmbH
*
* 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.
*/
import java.util.Arrays;
import java.util.ruparator;
import java.util.Iterator;
import java.util.List;
/**
* Utility class providing some useful static sort methods. The sort routines
* all return index permutations p such that data[p[0]],..,data[p[data.length-1]]
* is in sorted order. The data array itself is not modified.
* To actually rearrange the array elements, the inverse of p can be used to
* permute the array, such that data[0],..,data[data.length-1] is in sorted
* order. Use <code>getIterator(p, data)</code> to iterate in sorted order.
* A code example may show you what to do next:
* <pre>
* String[] colors = { "red", "green", "blue" };
* int[] p = SortUtils.sort(colors, new StringComparator());
* // --> (colors[p[0]], colors[p[1]], colors[p[2]]) == ("blue","green","red")
* Iterator iter = SortUtils.getIterator(p, colors)
* // --> (iter.next(), iter.next(), iter.next()) == ("blue","green","red")
* SortUtils.permute(SortUtils.inverse(p), colors, true);
* // --> (colors[0], colors[1], colors[2]) == ("blue","green","red")
* </pre>
* Stable sorts (preserving order of equal elements) are supported.
* Sorting is done using quick-sort mith median of 3 (and insertion-sort
* for small ranges).
*
* @author Christoph Beck
*/
public class SortUtils {
/**
* Helper class used to perform quicksort.
*
* @author Christoph Beck
*/
static final class QuickSorter {
private static final int INSERTIONSORT_THRESHOLD = 7;
private final Object[] data;
QuickSorter(Object[] data) {
this.data = data;
}
private int compare(Comparator cmp, boolean stable, int i, int j) {
int result = cmp.rupare(data[i], data[j]);
if (result == 0 && stable && i != j) {
result = i < j ? -1 : 1;
}
return result;
}
private int med3(Comparator cmp, int a, int b, int c) {
return (compare(cmp, false, a, b) < 0 ?
(compare(cmp, false, b, c) < 0 ? b : compare(cmp, false, a, c) < 0 ? c : a) :
(compare(cmp, false, b, c) > 0 ? b : compare(cmp, false, a, c) < 0 ? c : a));
}
private int pivot(int[] indices, Comparator cmp, int lo, int hi) {
return med3(cmp, indices[lo + 1], indices[(lo + hi) / 2], indices[hi - 1]);
}
private void swap(int[] indices, int i, int j) {
int tmp = indices[i];
indices[i] = indices[j];
indices[j] = tmp;
}
private void insertionSort(int[] indices, Comparator cmp, boolean stable, int lo, int hi) {
for (int i = lo; i <= hi; i++) {
for (int j = i; j > lo && compare(cmp, stable, indices[j-1], indices[j]) > 0; j--) {
swap(indices, j-1, j);
}
}
}
private void quickSort(int[] indices, Comparator cmp, boolean stable, int lo0, int hi0) {
int pivot = pivot(indices, cmp, lo0, hi0);
int lo = lo0, hi = hi0;
while (lo <= hi) {
while (lo < hi0 && compare(cmp, stable, pivot, indices[lo]) > 0)
++lo;
while (hi > lo0 && compare(cmp, stable, pivot, indices[hi]) < 0)
--hi;
if (lo <= hi) {
swap(indices, lo++, hi--);
}
}
sort(indices, cmp, stable, lo0, hi);
sort(indices, cmp, stable, lo, hi0);
}
void sort(int[] indices, Comparator cmp, boolean stable, int lo, int hi) {
if (hi - lo < INSERTIONSORT_THRESHOLD) {
insertionSort(indices, cmp, stable, lo, hi);
} else {
quickSort(indices, cmp, stable, lo, hi);
}
}
void sort(int[] indices, Comparator cmp, boolean stable) {
sort(indices, cmp, stable, 0, indices.length - 1);
}
int[] sort(Comparator cmp, boolean stable) {
int[] indices = identity(data.length);
sort(indices, cmp, stable);
return indices;
}
}
/**
* Create identity permutation, that is <code>{0, 1, ..., n}</code>
*/
public static int[] identity(int n) {
int[] indices = new int[n];
for (int i = 0; i < n; i++)
indices[i] = i;
return indices;
}
/**
* Create reverse permutation, that is <code>{n-1, .... 1, 0}</code>
*/
public static int[] reverse(int n) {
int[] indices = new int[n];
for (int i = 0; i < n; i++)
indices[i] = n - i - 1;
return indices;
}
/**
* Compute inverse permutation
*/
public static int[] inverse(int[] p) {
int[] pi = new int[p.length];
for (int i = 0; i < pi.length; i++)
pi[p[i]] = i;
return pi;
}
/**
* Rearrange the specified data according to the specified permutation.
* That is, the array is rearranged, such that
* <code>data_after[p[i]] == data_before[i]</code>.
* @param data data to be permuted
* @param p the permutation
* @param clone if true, rearrange a clone instead of the original data;
* @return the permuted array (which is the original reference if clone == false)
*/
public static Object[] permute(int[] p, Object[] data, boolean clone) {
Object[] permuted = null;
if (clone) {
permuted = (Object[])data.clone();
for (int i = 0; i < data.length; i++)
permuted[p[i]] = data[i];
} else {
// run thru cycles
int i = 0;
while (i < p.length) {
if (p[i] < 0 || p[i] == i) // skip already handled and cycles of length 1
++i;
else { // start a new cycle
int j = p[i];
Object save = data[i];
while (p[j] >= 0) {
Object tmp = data[j];
data[j] = save;
save = tmp;
i = j;
j = p[j];
p[i] = -1;
}
}
}
permuted = data;
}
return permuted;
}
/**
* Answer iterator, which iterates over specified data array according
* to the specified permutation, that is
* <code>data[p[0]],..,data[p[data.length-1]]</code>
*/
public static Iterator getIterator(final int[] p, final Object[] data) {
return new Iterator() {
int pos = 0;
public boolean hasNext() {
return pos < data.length;
}
public Object next() {
return data[p[pos++]];
}
public void remove() {
throw new UnsupportedOperationException("Cannot remove from immutable iterator!");
}
};
}
/**
* Answer iterator, which iterates over specified data list according
* to the specified permutation, that is
* <code>data.get(p[0]),..,data.get(p[data.length-1])</code>
*/
public static Iterator getIterator(final int[] p, final List data) {
return new Iterator() {
int pos = 0;
public boolean hasNext() {
return pos < data.size();
}
public Object next() {
return data.get(p[pos++]);
}
public void remove() {
throw new UnsupportedOperationException("Cannot remove from immutable iterator!");
}
};
}
// /**
// * An improved heap builder.
// * Assumes children of i at 2i and 2i+1 (requires i>0)
// */
// private static void cheap(int[] indices, Object[] data, Comparator comparator, int i, int j) {
// int k = (i << 1);
// if (k > j)
// return;
// while (k < j) {
// if (comparator.rupare(data[indices[k]], data[indices[k + 1]]) < 0)
// k++;
// k <<= 1;
// }
// if (k > j)
// k >>= 1;
// while (comparator.rupare(data[indices[k]], data[indices[i]]) < 0)
// k >>= 1;
// int t1 = indices[i], t2;
// while (k > i) {
// t2 = indices[k];
// indices[k] = t1;
// k >>= 1;
// t1 = indices[k];
// indices[k] = t2;
// k >>= 1;
// }
// if (k == i)
// indices[i] = t1;
// }
//
// /**
// * Do a (clever) heapsort.
// *
// * @param comparator Comparator object specifying the sort order.
// */
// public static void cheapSort(int[] indices, Object[] data, Comparator comparator) {
// int n = data.length;
// if (n > 1) {
// int i;
// int m = 0;
// for (i = 1; i < n; i++)
// if (comparator.rupare(data[indices[i]], data[indices[m]]) < 0)
// m = i;
// if (m > 0) {
// int t = indices[0];
// indices[0] = indices[m];
// indices[m] = t;
// }
// if (n > 2) {
// for (i = n / 2; i > 1; i--)
// cheap(indices, data, comparator, i, n - 1);
// for (i = n - 1; i > 1; i--) {
// cheap(indices, data, comparator, 1, i);
// int t = indices[1];
// indices[1] = indices[i];
// indices[i] = t;
// }
// }
// }
// }
//
// /**
// * Perform a cheapsort
// */
// public static int[] cheapSort(Object[] data, Comparator comparator) {
// int[] indices = identity(data.length);
// cheapSort(indices, data, comparator);
// return indices;
// }
/**
* Do a sort on indices.
* @param data data to be sorted
* @param comparator comparator to use
* @param stable do a stable sort iff true
* @param indices into data (any permutation of 0,..data.length-1).
*/
public static void sort(int[] indices, Object[] data, Comparator comparator, boolean stable) {
new QuickSorter(data).sort(indices, comparator, stable);
}
/**
* Do a sort on indices.
* @param data data to be sorted
* @param comparator comparator to use
* @param stable do a stable sort iff true
* @return permutation p such that data[p[0]],..,data[p[data.length-1]] is in sorted order
*/
public static int[] sort(Object[] data, Comparator comparator, boolean stable) {
int[] indices = identity(data.length);
sort(indices, data, comparator, stable);
return indices;
}
/**
* Do an unstable sort.
* @param data data to be sorted
* @param comparator comparator to use
* @return permutation p such that data[p[0]],..,data[p[data.length-1]] is in sorted order
*/
public static int[] sort(Object[] data, Comparator comparator) {
return sort(data, comparator, false);
}
/**
* Do an unstable sort.
* @param data data to be sorted
* @param indices into data (permutation of 0,..data.length-1).
*/
public static void sort(int[] indices, Object[] data, Comparator comparator) {
sort(indices, data, comparator, false);
}
/**
* Test method
*/
public static void main(String[] args) {
Comparator cmp = new Comparator() {
public int compare(Object o1, Object o2) {
return ((Comparable)o1).rupareTo(o2);
}
};
int n = 1000000;
if (args.length == 1)
try {
n = Integer.parseInt(args[0]);
} catch (Exception e) {
System.err.println(e);
}
System.out.println("Generating " + n + " random integers...");
java.util.Random random = new java.util.Random();
Integer[] data = new Integer[n];
for (int i = 0; i < n; i++) {
data[i] = new Integer(Math.abs(random.nextInt()));
// data[i] = new Integer(i);
}
int[] indices;
long time;
System.out.print("Arrays.sort...");
time = System.currentTimeMillis();
Integer[] clone = (Integer[])data.clone();
Arrays.sort(clone, cmp);
System.out.println(System.currentTimeMillis()-time + "ms");
System.out.print("quicksort...");
indices = identity(n);
time = System.currentTimeMillis();
sort(indices, data, cmp, false);
System.out.println(System.currentTimeMillis()-time + "ms");
for (int i = 1; i < n; i++)
if (cmp.rupare(data[indices[i-1]], data[indices[i]]) > 0)
System.err.println("proplem: quickSort at " + i);
System.out.print("quicksort stable...");
// indices = identity(n);
time = System.currentTimeMillis();
sort(indices, data, cmp, true);
System.out.println(System.currentTimeMillis()-time + "ms");
for (int i = 1; i < n; i++) {
int res = cmp.rupare(data[indices[i-1]], data[indices[i]]);
if (res > 0)
System.err.println("proplem: quickSort stable at " + i);
if (res == 0 && indices[i-1] > indices[i])
System.err.println("proplem: quickSort stable (not stable) at " + i);
}
// System.out.print("cheapsort...");
// time = System.currentTimeMillis();
// indices = cheapSort(data, cmp);
// System.out.println(System.currentTimeMillis()-time + "ms");
// for (int i = 1; i < n; i++)
// if (cmp.rupare(data[indices[i-1]], data[indices[i]]) > 0)
// System.err.println("proplem: cheapSort at " + i);
System.out.print("permutate copy...");
time = System.currentTimeMillis();
Object[] data_copy = permute(inverse(indices), data, true);
System.out.println(System.currentTimeMillis()-time + "ms");
for (int i = 1; i < n; i++)
if (cmp.rupare(data_copy[i-1], data_copy[i]) > 0)
System.err.println("proplem: permute copy at " + i);
System.out.print("permutate original...");
time = System.currentTimeMillis();
permute(inverse(indices), data, false);
System.out.println(System.currentTimeMillis()-time + "ms");
for (int i = 1; i < n; i++)
if (cmp.rupare(data[i-1], data[i]) > 0)
System.err.println("proplem: permute original at " + i);
}
}
Sort array values in descending order
import java.util.Arrays;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
Integer[] points = new Integer[5];
points[0] = 4;
points[1] = 3;
points[2] = 0;
points[3] = 4;
points[4] = 4;
Arrays.sort(points);
System.out.println(Arrays.toString(points));
Arrays.sort(points, Collections.reverseOrder());
System.out.println(Arrays.toString(points));
}
}
/*[0, 3, 4, 4, 4]
[4, 4, 4, 3, 0]
*/
Sorting an Array
import java.util.Arrays;
import java.util.Collections;
public class Main {
public static void main(String[] argv) throws Exception {
int[] intArray = new int[] { 4, 1, 3, -23 };
Arrays.sort(intArray);
// [-23, 1, 3, 4]
String[] strArray = new String[] { "z", "a", "C" };
Arrays.sort(strArray);
// [C, a, z]
// Case-insensitive sort
Arrays.sort(strArray, String.CASE_INSENSITIVE_ORDER);
// [a, C, z]
// Reverse-order sort
Arrays.sort(strArray, Collections.reverseOrder());
// [z, a, C]
// Case-insensitive reverse-order sort
Arrays.sort(strArray, String.CASE_INSENSITIVE_ORDER);
Collections.reverse(Arrays.asList(strArray));
// [z, C, 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
*/
Sort in reverse order
import java.util.Arrays;
import java.util.Collections;
public class Main {
public static void main(String args[]) {
String[] myArray = new String[] { "A", "a", "B" };
Arrays.sort (myArray, Collections.reverseOrder());
System.out.println(Arrays.toString(myArray));
}
}
//[a, B, A]