Java Tutorial/Collections/Array Reflection Utilities

Материал из Java эксперт
Перейти к: навигация, поиск

Array Getter and Setter Methods

GETTER METHODSSETTER METHODSget(Object array, int index)set(Object array, int index, Object value)getBoolean(Object array, int index)setBoolean(Object array, int index, boolean value)getByte(Object array, int index)setByte(Object array, int index, byte value)getChar(Object array, int index)setChar(Object array, int index, char value)getDouble(Object array, int index)setDouble(Object array, int index, double value)getFloat(Object array, int index)setFloat(Object array, int index, float value)getInt(Object array, int index)setInt(Object array, int index, int value)getLong(Object array, int index)setLong(Object array, int index, long value)getShort(Object array, int index)setShort(Object array, int index, short value)


Checking Equality

   <source lang="java">

public static boolean equals(boolean a[], boolean array2[]) public static boolean equals(byte array1[], byte array2[]) public static boolean equals(char array1[], char array2[]) public static boolean equals(double array1[], double array2[]) public static boolean equals(float array1[], float array2[]) public static boolean equals(int array1[], int array2[]) public static boolean equals(long array1[], long array2[]) public static boolean equals(short array1[], short array2[]) public static boolean equals(Object array1[], Object array2[])</source>



false


Doubling the size of an array: double the size of any type of array

   <source lang="java">

import java.lang.reflect.Array; public class MainClass {

 public static void main (String args[]) {
   int[] array = (int[])Array.newInstance(int.class, 3);
   for(int i=0;i<array.length;i++){
     array[i] = i;
     
   }    
   
   int[] arrayDoubled = (int[])doubleArray(array);
   for (int i: arrayDoubled) {
     System.out.println(i);
   }
 }
 static Object doubleArray(Object original) {
   Object returnValue = null;
   Class type = original.getClass();
   if (type.isArray()) {
     int length = Array.getLength(original);
     Class elementType = type.getComponentType();
     returnValue = Array.newInstance(elementType, length*2);
     System.arraycopy(original, 0, returnValue, 0, length);
   }
   return returnValue;
 }

}</source>



0
1
2
0
0
0


Filling Arrays method signature

   <source lang="java">

public static void fill(boolean a[], boolean val) public static void fill(boolean a[], int fromIndex, int toIndex, boolean val) public static void fill(byte a[], byte val) public static void fill(byte a[], int fromIndex, int toIndex, byte val) public static void fill(char a[], char val) public static void fill(char a[], int fromIndex, int toIndex, char val) public static void fill(double a[], double val) public static void fill(double a[], int fromIndex, int toIndex, double val) public static void fill(float a[], float val) public static void fill(float a[], int fromIndex, int toIndex, float val) public static void fill(int a[], int val) public static void fill(int a[], int fromIndex, int toIndex, int val) public static void fill(long a[], long val) public static void fill(long a[], int fromIndex, int toIndex, long val) public static void fill(short a[], short val) public static void fill(short a[], int fromIndex, int toIndex, short val) public static void fill(Object a[], Object val) public static void fill(Object a[], int fromIndex, int toIndex, Object val)</source>



100
100
100
100
100
100
100
100
100
100
100
100
100
50
50
50
100
100
100
100


Filling byte array

   <source lang="java">

import java.util.Arrays; public class MainClass {

 public static void main(String[] a) {
   byte array[] = new byte[10];

// Arrays.fill(array, 4); // illegal

   for (int i : array) {
     System.out.println(i);
   }
   Arrays.fill(array, (byte) 4); // Okay
   for (int i : array) {
     System.out.println(i);
   }
 }

}</source>



0
0
0
0
0
0
0
0
0
0
4
4
4
4
4
4
4
4
4
4


Get array length using reflection method

   <source lang="java">

import java.lang.reflect.Array; public class MainClass {

 public static void main (String args[]) {
   int[] array = (int[])Array.newInstance(int.class, 3);
   for(int i=0;i<array.length;i++){
     array[i] = i;
     
   }    
   
   int length = Array.getLength(array);
   for (int i=0; i<length; i++) {
     int value = Array.getInt(array, i);
     System.out.println("Position: " + i + ", value: " + value);
   }
 }

}</source>



Position: 0, value: 0
Position: 1, value: 1
Position: 2, value: 2


To fill part of array with object value, starting at array[fromIndex] up to and including array[toIndex-1]

   <source lang="java">

import java.util.Arrays; class Person implements Comparable<Person> {

 public Person(String firstName, String surname) {
   this.firstName = firstName;
   this.surname = surname;
 }
 public String toString() {
   return firstName + " " + surname;
 }
 public int compareTo(Person person) {
   int result = surname.rupareTo(person.surname);
   return result == 0 ? firstName.rupareTo(((Person) person).firstName) : result;
 }
 private String firstName;
 private String surname;

} public class MainClass {

 public static void main(String[] a) {
   Person[] people = new Person[100];
   Arrays.fill(people, 0, 50, new Person("A", "B"));
   Arrays.fill(people, 50, 100, new Person("C", "D"));
   for (Person person : people) {
     System.out.println(person);
   }
 }

}</source>



A B
A B
A B
A B
A B
A B
A B
A B
A B
A B
A B
A B
A B
A B
A B
A B
A B
A B
A B
A B
A B
A B
A B
A B
A B
A B
A B
A B
A B
A B
A B
A B
A B
A B
A B
A B
A B
A B
A B
A B
A B
A B
A B
A B
A B
A B
A B
A B
A B
A B
C D
C D
C D
C D
C D
C D
C D
C D
C D
C D
C D
C D
C D
C D
C D
C D
C D
C D
C D
C D
C D
C D
C D
C D
C D
C D
C D
C D
C D
C D
C D
C D
C D
C D
C D
C D
C D
C D
C D
C D
C D
C D
C D
C D
C D
C D
C D
C D
C D
C D


Use Arrays.asList to convert array to generic list

   <source lang="java">

/*

* Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
*   - Redistributions of source code must retain the above copyright
*     notice, this list of conditions and the following disclaimer.
*
*   - Redistributions in binary form must reproduce the above copyright
*     notice, this list of conditions and the following disclaimer in the
*     documentation and/or other materials provided with the distribution.
*
*   - Neither the name of Sun Microsystems nor the names of its
*     contributors may be used to endorse or promote products derived
*     from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

import java.util.Arrays; import java.util.Collections; import java.util.List; public class Sort {

 public static void main(String[] args) {
   List<String> list = Arrays.asList(args);
   Collections.sort(list);
   System.out.println(list);
 }

}</source>





Use Arrays.asList to convert array to list

   <source lang="java">

import java.util.Arrays; import java.util.List; import java.util.ListIterator; public class MainClass {

 static void listTrim(List<String> strings) {
   for (ListIterator<String> lit = strings.listIterator(); lit.hasNext();) {
     lit.set(lit.next().trim());
   }
 }
 public static void main(String[] args) {
   List<String> l = Arrays.asList(" red ", " white ", " blue ");
   listTrim(l);
   for (String s : l) {
     System.out.format("\"%s\"%n", s);
   }
 }

}</source>





Use Arrays.equals to compare arrays

   <source lang="java">

/*

* Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
*   - Redistributions of source code must retain the above copyright
*     notice, this list of conditions and the following disclaimer.
*
*   - Redistributions in binary form must reproduce the above copyright
*     notice, this list of conditions and the following disclaimer in the
*     documentation and/or other materials provided with the distribution.
*
*   - Neither the name of Sun Microsystems nor the names of its
*     contributors may be used to endorse or promote products derived
*     from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

import java.io.Console; import java.io.IOException; import java.util.Arrays; public class Password {

 public static void main(String args[]) throws IOException {
   Console c = System.console();
   if (c == null) {
     System.err.println("No console.");
     System.exit(1);
   }
   String login = c.readLine("Enter your login: ");
   char[] oldPassword = c.readPassword("Enter your old password: ");
   if (verify(login, oldPassword)) {
     boolean noMatch;
     do {
       char[] newPassword1 = c.readPassword("Enter your new password: ");
       char[] newPassword2 = c.readPassword("Enter new password again: ");
       noMatch = !Arrays.equals(newPassword1, newPassword2);
       if (noMatch) {
         c.format("Passwords don"t match. Try again.%n");
       } else {
         change(login, newPassword1);
         c.format("Password for %s changed.%n", login);
       }
       Arrays.fill(newPassword1, " ");
       Arrays.fill(newPassword2, " ");
     } while (noMatch);
   }
   Arrays.fill(oldPassword, " ");
 }
 // Dummy verify method.
 static boolean verify(String login, char[] password) {
   return true;
 }
 // Dummy change method.
 static void change(String login, char[] password) {
 }

}</source>





Use Arrays.fill to set values of array

   <source lang="java">

/*

* Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
*   - Redistributions of source code must retain the above copyright
*     notice, this list of conditions and the following disclaimer.
*
*   - Redistributions in binary form must reproduce the above copyright
*     notice, this list of conditions and the following disclaimer in the
*     documentation and/or other materials provided with the distribution.
*
*   - Neither the name of Sun Microsystems nor the names of its
*     contributors may be used to endorse or promote products derived
*     from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

import java.io.Console; import java.io.IOException; import java.util.Arrays; public class Password {

 public static void main(String args[]) throws IOException {
   Console c = System.console();
   if (c == null) {
     System.err.println("No console.");
     System.exit(1);
   }
   String login = c.readLine("Enter your login: ");
   char[] oldPassword = c.readPassword("Enter your old password: ");
   if (verify(login, oldPassword)) {
     boolean noMatch;
     do {
       char[] newPassword1 = c.readPassword("Enter your new password: ");
       char[] newPassword2 = c.readPassword("Enter new password again: ");
       noMatch = !Arrays.equals(newPassword1, newPassword2);
       if (noMatch) {
         c.format("Passwords don"t match. Try again.%n");
       } else {
         change(login, newPassword1);
         c.format("Password for %s changed.%n", login);
       }
       Arrays.fill(newPassword1, " ");
       Arrays.fill(newPassword2, " ");
     } while (noMatch);
   }
   Arrays.fill(oldPassword, " ");
 }
 // Dummy verify method.
 static boolean verify(String login, char[] password) {
   return true;
 }
 // Dummy change method.
 static void change(String login, char[] password) {
 }

}</source>





Use Arrays.sort to sort an array

   <source lang="java">

/*

* Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
*   - Redistributions of source code must retain the above copyright
*     notice, this list of conditions and the following disclaimer.
*
*   - Redistributions in binary form must reproduce the above copyright
*     notice, this list of conditions and the following disclaimer in the
*     documentation and/or other materials provided with the distribution.
*
*   - Neither the name of Sun Microsystems nor the names of its
*     contributors may be used to endorse or promote products derived
*     from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.ruparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; public class Anagrams2 {

 public static void main(String[] args) {
   int minGroupSize = Integer.parseInt(args[1]);
   // Read words from file and put into simulated multimap
   Map<String, List<String>> m = new HashMap<String, List<String>>();
   try {
     Scanner s = new Scanner(new File(args[0]));
     while (s.hasNext()) {
       String word = s.next();
       String alpha = alphabetize(word);
       List<String> l = m.get(alpha);
       if (l == null)
         m.put(alpha, l = new ArrayList<String>());
       l.add(word);
     }
   } catch (IOException e) {
     System.err.println(e);
     System.exit(1);
   }
   // Make a List of all permutation groups above size threshold
   List<List<String>> winners = new ArrayList<List<String>>();
   for (List<String> l : m.values())
     if (l.size() >= minGroupSize)
       winners.add(l);
   // Sort permutation groups according to size
   Collections.sort(winners, new Comparator<List<String>>() {
     public int compare(List<String> o1, List<String> o2) {
       return o2.size() - o1.size();
     }
   });
   // Print permutation groups
   for (List<String> l : winners) {
     System.out.println(l.size() + ": " + l);
   }
 }
 private static String alphabetize(String s) {
   char[] a = s.toCharArray();
   Arrays.sort(a);
   return new String(a);
 }

}</source>





Using a Utility Method in java.util.Arrays class to Initialize an Array

   <source lang="java">

import java.util.Arrays; public class MainClass {

 public static void main(String[] arg) {
   double[] data = new double[50]; // An array of 50 values of type double
   Arrays.fill(data, 1.0);                     // Fill all elements of data with 1.0
   
   for (int i = 0; i < data.length; i++) { // i from 0 to data.length-1
     System.out.println(data[i]);
   }
   
 }

}</source>



1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0


Using reflection method to create new instance for an Array

   <source lang="java">

import java.lang.reflect.Array; public class MainClass {

 public static void main (String args[]) {
   int array[] = (int[])Array.newInstance(int.class, 5);
   for(int i: array){
     System.out.println(i);
     
   }
 }

}</source>



0
0
0
0
0


Using reflection method to create new instance for a two dimensional Array

   <source lang="java">

import java.lang.reflect.Array; public class MainClass {

 public static void main (String args[]) {
   int dimensions[] = {3, 4};
   int array[][] = (int[][])Array.newInstance(int.class, dimensions);
   for(int[] inner: array){
     for(int i: inner ){
       System.out.println(i);  
     }
   }
 }

}</source>



0
0
0
0
0
0
0
0
0
0
0
0


Using reflection to check array type and length

   <source lang="java">

import java.lang.reflect.Array; public class MainClass {

 public static void main (String args[]) {
   int[] object = {1,2,3};
   Class type = object.getClass();
   if (type.isArray()) {
     Class elementType = type.getComponentType();
     System.out.println("Array of: " + elementType);
     System.out.println("Length: " + Array.getLength(object));
   }
 }

}</source>



Array of: int
Length: 3


Using reflection to create, fill, and display an array

   <source lang="java">

import java.lang.reflect.Array; public class MainClass {

 public static void main (String args[]) {
   Object array = Array.newInstance(int.class, 3);
   int length = Array.getLength(array);
   for (int i=0; i<length; i++) {
     int value = i;
     Array.setInt(array, i, value);
   }
   
   for(int i: (int[]) array){
     System.out.println(i);
     
   }
 }

}</source>



0
1
2