Why is this java array java method not working?
When I start thinking, I am using the wrong book for teaching. I copied this word for word from Sam Learn Java but the method is .sort(names);
undefined for the array type.
I feel like it has to do with a challenge public static void main(String[] args) {
, but I don't know how to change it.
package arrays;
import java.util.*;
public class Arrays {
public static void main(String[] args) {
String names[] = { "Lauren", "Audrina", "Heidi", "Whitney",
"Stephanie", "Spencer", "Lisa", "Brody", "Frankie", "Holly",
"Jordan", "Brian", "Jason" };
System.out.println("The original order:");
for (int i = 0; i < names.length; i++) {
System.out.print(i + ": " + names[i] + " ");
}
Arrays.sort(names);
System.out.println("\nThe new order:");
for (int i = 0; i < names.length; i++) {
System.out.print(i + ": " + names[i] + " ");
}
System.out.println();
}
}
source to share
( Thomas pointed to the answer, but since it was a comment you can't accept it, here's CW you can accept.)
Arrays
is a class in a package java.util
that has a method sort
. By calling your own class Arrays
, you are hiding java.util
one of your code (this is sometimes called "shading"), so the line Arrays.sort(names);
tries to use a method sort
for yours (and it doesn't).
To fix this, you have three options:
-
Change your class name (
ArrayTest
whatever) or -
Change your call to
sort
:java.util.Arrays.sort(names);
(so the compiler knows what you are talking aboutjava.util.Arrays
, not your class) or -
Use
import static java.util.Arrays.sort;
to import a methodsort
, not a classArrays
, and call it withsort(names);
(without the name of the previous class).
source to share