Java/Language Basics/Varargs

Материал из Java эксперт
Версия от 18:01, 31 мая 2010; (обсуждение)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Convert varargs to an array

 
public class Main {
  public static void main(String[] args) {
    printMessage("H", "Y", ", ", "how ", "are ", "you", "?");
  }
  public static void printMessage(String... messages) {
    String[] copiedMessage = messages;
    for (int i = 0; i < messages.length; i++) {
      System.out.print(copiedMessage[i]);
    }
  }
}





Create a method that accept varargs in Java

  
public class Main {
  public static void main(String[] args) {
    printParams(1, 2, 3);
    printParams(10, 20, 30, 40, 50);
    printParams(100, 200, 300, 400, 500);
  }
  public static void printParams(int... numbers) {
    for (int number : numbers) {
      System.out.println(number + ", ");
    }
  }
}





Demonstrate variable length arguments.

  
public class VarArgs {
  static void vaTest(int... v) {
    System.out.print("Number of args: " + v.length + " Contents: ");
    for (int x : v)
      System.out.print(x + " ");
    System.out.println();
  }
  public static void main(String args[]) {
    // vaTest() can be called with a variable number of arguments.
    vaTest(10); // 1 arg
    vaTest(1, 2, 3); // 3 args
    vaTest(); // no args
  }
}





Java enum and varargs

  
/*
License for Java 1.5 "Tiger": A Developer"s Notebook
     (O"Reilly) example package
Java 1.5 "Tiger": A Developer"s Notebook (O"Reilly) 
by Brett McLaughlin and David Flanagan.
ISBN: 0-596-00738-8
You can use the examples and the source code any way you want, but
please include a reference to where it comes from if you use it in
your own products or services. Also note that this software is
provided by the author "as is", with no expressed or implied warranties. 
In no event shall the author be liable for any direct or indirect
damages arising in any way out of the use of this software.
*/

import java.util.List;
enum GuitarInlay {
  NO_INLAY,
  DIAMONDS_AND_SQUARES,
  DOTS,
  TINY_DOTS,
  ABALONE_BORDER,
  ABALONE_ROSETTE
}
enum GuitarWood {
  MAHOGANY,
  INDIAN_ROSEWOOD,
  BRAZILIAN_ROSEWOOD,
  MADAGASCAR_ROSEWOOD,
  ZIRICOTE,
  BUBINGA,
  KOA,
  
  ADIRONDACK,
  SITKA,
  CEDAR,
  REDWOOD
}
public class Guitar {
  private String builder;
  private String model;
  private float nutWidth;
  private GuitarWood backSidesWood;
  private GuitarWood topWood;
  private GuitarInlay fretboardInlay;
  private GuitarInlay topInlay;
  private List features;
  private static final float DEFAULT_NUT_WIDTH = 1.6875f;
  public Guitar(String builder, String model, String... features) {
    this(builder, model, null, null, DEFAULT_NUT_WIDTH, null, null, features);
  }
  public Guitar(String builder, String model, 
                GuitarWood backSidesWood, GuitarWood topWood,
                float nutWidth, String... features) {
    this(builder, model, backSidesWood, topWood, nutWidth, null, null, features);
  }
  public Guitar(String builder, String model, 
                GuitarWood backSidesWood, GuitarWood topWood,
                float nutWidth, 
                GuitarInlay fretboardInlay, GuitarInlay topInlay, 
                String... features) {
    this.builder = builder;
    this.model = model;
    this.backSidesWood = backSidesWood;
    this.topWood = topWood;
    this.nutWidth = nutWidth;
    this.fretboardInlay = fretboardInlay;
    this.topInlay = topInlay;
    this.features = java.util.Arrays.asList(features);
  }
}





Java varargs: Iterating Over Variable Length Argument Lists

  
/*
License for Java 1.5 "Tiger": A Developer"s Notebook
     (O"Reilly) example package
Java 1.5 "Tiger": A Developer"s Notebook (O"Reilly) 
by Brett McLaughlin and David Flanagan.
ISBN: 0-596-00738-8
You can use the examples and the source code any way you want, but
please include a reference to where it comes from if you use it in
your own products or services. Also note that this software is
provided by the author "as is", with no expressed or implied warranties. 
In no event shall the author be liable for any direct or indirect
damages arising in any way out of the use of this software.
*/

public class MathUtils {
  public static int max(int... values) {
    if (values.length == 0) {
      throw new IllegalArgumentException("No values supplied.");
    }
    int max = Integer.MIN_VALUE;
    for (int i : values) {
      if (i > max)
        max = i;
    }
    return max;
  }
}





Java Varargs Tester

  
/*
License for Java 1.5 "Tiger": A Developer"s Notebook
     (O"Reilly) example package
Java 1.5 "Tiger": A Developer"s Notebook (O"Reilly) 
by Brett McLaughlin and David Flanagan.
ISBN: 0-596-00738-8
You can use the examples and the source code any way you want, but
please include a reference to where it comes from if you use it in
your own products or services. Also note that this software is
provided by the author "as is", with no expressed or implied warranties. 
In no event shall the author be liable for any direct or indirect
damages arising in any way out of the use of this software.
*/

import java.io.IOException;
import java.io.PrintStream;
import java.util.LinkedList;
import java.util.List;
public class VarargsTester {
  public VarargsTester() {
  }
  private int[] getListOfNumbers() {
    int[] numbers = new int[] {0, 2, 4, 6, 8, 10, 9, 7, 5, 3, 1};
    return numbers;
  }
  private String print(Object... values) {
    StringBuilder sb = new StringBuilder();
    for (Object o : values) {
      sb.append(o.toString())
        .append(" ");
    }
    return sb.toString();
  }
  public void testMaxMethod(PrintStream out) throws IOException {
    int[] numbers = getListOfNumbers();
    int max = MathUtils.max(numbers);
    out.println("Max of list is: " + max);
  }
  public void testPrintMethod(PrintStream out) throws IOException {
    out.println(print("foo", 23, -12, 1.23, getListOfNumbers()));
  }
  public void testArrayArgs(PrintStream out) throws IOException {
    Object[] obj = new String[] {"Hello", "to", "all", "of", "you"};
    out.printf("%s\n", obj);
    out.printf("%s\n", (Object)obj);
  }
  public static void main(String[] args) {
    try {
      VarargsTester tester = new VarargsTester();
      tester.testMaxMethod(System.out);
      tester.testPrintMethod(System.out);
      tester.testArrayArgs(System.out);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}





New parameter for main method

 
public class Main {
  public static void main(String... args) {
    for (String arg : args) {
      System.out.println(arg);
    }
  }
}





Old style: Use an array to pass a variable number of arguments

  
public class PassArray {
  static void vaTest(int v[]) {
    System.out.print("Number of args: " + v.length + " Contents: ");
    for (int x : v)
      System.out.print(x + " ");
    System.out.println();
  }
  public static void main(String args[]) {
    int n1[] = { 10 };
    int n2[] = { 1, 2, 3 };
    int n3[] = {};
    vaTest(n1); // 1 arg
    vaTest(n2); // 3 args
    vaTest(n3); // no args
  }
}





Use varargs with standard arguments.

  
public class VarArgs2 {
  static void vaTest(String msg, int... v) {
    System.out.print(msg + v.length + " Contents: ");
    for (int x : v)
      System.out.print(x + " ");
    System.out.println();
  }
  public static void main(String args[]) {
    vaTest("One vararg: ", 10);
    vaTest("Three varargs: ", 1, 2, 3);
    vaTest("No varargs: ");
  }
}





Varargs and overloading.

  
/*
Java 2, v5.0 (Tiger) New Features
by Herbert Schildt
ISBN: 0072258543
Publisher: McGraw-Hill/Osborne, 2004
*/
public class VarArgs3 { 
 
  static void vaTest(int ... v) { 
    System.out.print("vaTest(int ...): " + "Number of args: " + v.length + 
                     " Contents: "); 
 
    for(int x : v) 
      System.out.print(x + " "); 
 
    System.out.println(); 
  } 
 
  static void vaTest(boolean ... v) { 
    System.out.print("vaTest(boolean ...) " + 
                     "Number of args: " + v.length + 
                     " Contents: "); 
 
    for(boolean x : v) 
      System.out.print(x + " "); 
 
    System.out.println(); 
  } 
 
  static void vaTest(String msg, int ... v) { 
    System.out.print("vaTest(String, int ...): " + 
                     msg + v.length + 
                     " Contents: "); 
 
    for(int x : v) 
      System.out.print(x + " "); 
 
    System.out.println(); 
  } 
 
  public static void main(String args[])  
  { 
    vaTest(1, 2, 3);  
    vaTest("Testing: ", 10, 20); 
    vaTest(true, false, false); 
  } 
}





VarArgs Example

  
public class VarArgsExample {
    int sumArrays(int[]... intArrays)
    {
        int sum, i, j;
        sum=0;
        for(i=0; i<intArrays.length; i++) {
            for(j=0; j<intArrays[i].length; j++) {
                sum += intArrays[i][j];
            }
        }
        return(sum);
    }
    public static void main(String args[])
    {
        VarArgsExample va = new VarArgsExample();
        int sum=0;
        sum = va.sumArrays(new int[]{1,2,3},
                           new int[]{4,5,6},
                           new int[]{100,200});
        System.out.println("The sum of the numbers is: " + sum);
    }
}





Varargs, overloading, and ambiguity.

  
public class VarArgs4 {
  static void vaTest(int... v) {
    System.out.print("vaTest(int ...): " + "Number of args: " + v.length + " Contents: ");
    for (int x : v)
      System.out.print(x + " ");
    System.out.println();
  }
  static void vaTest(boolean... v) {
    System.out.print("vaTest(boolean ...) " + "Number of args: " + v.length + " Contents: ");
    for (boolean x : v)
      System.out.print(x + " ");
    System.out.println();
  }
  public static void main(String args[]) {
    vaTest(1, 2, 3); // OK
    vaTest(true, false, false); // OK
    //vaTest(); // Error: Ambiguous!
  }
}