0% found this document useful (0 votes)
59 views

Array Getter and Setter Methods

Uploaded by

Javier Solis
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
59 views

Array Getter and Setter Methods

Uploaded by

Javier Solis
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

9.

 7. Array Reflection Utilities


9. 7. 1.  Array Getter and Setter Methods

9. 7. 2.  Filling Arrays method signature

9. 7. 3.  Filling byte array

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

9. 7. 5.  Using reflection method to create new instance for an Array


Using reflection method to create new instance for a two
9. 7. 6. 
dimensional Array
9. 7. 7.  Checking Equality

9. 7. 8.  Using reflection to check array type and length

9. 7. 9.  Using reflection to create, fill, and display an array

9. 7. 10.  Get array length using reflection method

9. 7. 11.  Doubling the size of an array: double the size of any type of array
To fill part of array with object value, starting at array[fromIndex] up
9. 7. 12. 
to and including array[toIndex-1]
9. 7. 13.  Use Arrays.asList to convert array to list

9. 7. 14.  Use Arrays.asList to convert array to generic list

9. 7. 15.  Use Arrays.sort to sort an array

9. 7. 16.  Use Arrays.equals to compare arrays

9. 7. 17.  Use Arrays.fill to set values of array

9. 7. 1. Array Getter and Setter Methods


GETTER METHODS SETTER METHODS
get(Object array, int index) set(Object array, int index, Object value)
getBoolean(Object array, int setBoolean(Object array, int index, boolean value)
index)
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)

9. 7. 2. Filling Arrays method signature


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)

import java.util.Arrays;
public class MainClass {
  public static void main(String[] a) {
    int array[] = new int[10];
    Arrays.fill(array, 100);
    for(int i: array){
      System.out.println(i);
    }
    Arrays.fill(array, 3, 6, 50);
    for(int i: array){
      System.out.println(i);
    }
  }
}

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

9. 7. 3. Filling byte array


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);
    }
  }
}

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

9. 7. 4. Using a Utility Method in java.util.Arrays class to Initialize an


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]);
    }
    
  }
}

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

9. 7. 5. Using reflection method to create new instance for an Array


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);
      
    }
  }
}

0
0
0
0
0

9. 7. 6. Using reflection method to create new instance for a two dimension


Array
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);  
      }
    }
  }
}

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

9. 7. 7. Checking Equality
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[])

import java.util.Arrays;
public class MainClass {
  public static void main(String[] a) {
    int[] i = new int[] { 1, 2, 3 };
    int[] j = new int[] { 1, 2, 4 };
    System.out.println(Arrays.equals(i, j));
  }
}

false

9. 7. 8. Using reflection to check array type and length


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));
    }
  }
}

Array of: int


Length: 3

9. 7. 9. Using reflection to create, fill, and display an array


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);
      
    }
  }
}

0
1
2

9. 7. 10. Get array length using reflection method


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);
    }
  }
}

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

9. 7. 11. Doubling the size of an array: double the size of any type of array
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;
  }

0
1
2
0
0
0

9. 7. 12. To fill part of array with object value, starting at array[fromIn


to and including array[toIndex-1]

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.compareTo(person.surname);
    return result == 0 ? firstName.compareTo(((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);
    }
  }
}

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

9. 7. 13. Use Arrays.asList to convert array to list


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);
    }
  }
}

9. 7. 14. Use Arrays.asList to convert array to generic list


/*
 * 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);
  }
}

9. 7. 15. Use Arrays.sort to sort an array


/*
 * 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.Comparator;
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);
  }
}

You might also like