Rectangle 27 3

You cannot have multiple inheritance in Java. However by using AOP you can have "limited" multiple inheritance. Try to google this to see some examples.

I also agree with Eyvid. Hannemann and Kiczales paper is great for learning the basics on design patterns and getting some great AOP examples.

aop - Aspect-oriented programming examples - Stack Overflow

aop
Rectangle 27 1761

Since Java 5 you can use Arrays.toString(arr) or Arrays.deepToString(arr) for arrays within arrays. Note that the Object[] version calls .toString() on each object in the array. The output is even decorated in the exact way you're asking.

String[] array = new String[] {"John", "Mary", "Bob"};
System.out.println(Arrays.toString(array));
[John, Mary, Bob]
String[][] deepArray = new String[][] {{"John", "Mary"}, {"Alice", "Bob"}};
System.out.println(Arrays.toString(deepArray));
//output: [[Ljava.lang.String;@106d69c, [Ljava.lang.String;@52e922]
System.out.println(Arrays.deepToString(deepArray));
[[John, Mary], [Alice, Bob]]
double[] doubleArray = { 7.0, 9.0, 5.0, 1.0, 3.0 };
System.out.println(Arrays.toString(doubleArray));
[7.0, 9.0, 5.0, 1.0, 3.0 ]
int[] intArray = { 7, 9, 5, 1, 3 };
System.out.println(Arrays.toString(intArray));
[7, 9, 5, 1, 3 ]

This works for multi dimensional arrays too.

What if we have an array of strings, and want simple output; like: String[] array = {"John", "Mahta", "Sara"}, and we want this output without bracket and commas: John Mahta Sara?

FYI, Arrays.deepToString() accepts only an Object [] (or an array of classes that extend Object, such as Integer, so it won't work on a primitive array of type int []. But Arrays.toString(<int array>) works fine for primitive arrays.

Don't forget to import the Arrays library with import java.util.Arrays;

What's the simplest way to print a Java array? - Stack Overflow

java arrays printing
Rectangle 27 1752

Since Java 5 you can use Arrays.toString(arr) or Arrays.deepToString(arr) for arrays within arrays. Note that the Object[] version calls .toString() on each object in the array. The output is even decorated in the exact way you're asking.

String[] array = new String[] {"John", "Mary", "Bob"};
System.out.println(Arrays.toString(array));
[John, Mary, Bob]
String[][] deepArray = new String[][] {{"John", "Mary"}, {"Alice", "Bob"}};
System.out.println(Arrays.toString(deepArray));
//output: [[Ljava.lang.String;@106d69c, [Ljava.lang.String;@52e922]
System.out.println(Arrays.deepToString(deepArray));
[[John, Mary], [Alice, Bob]]
double[] doubleArray = { 7.0, 9.0, 5.0, 1.0, 3.0 };
System.out.println(Arrays.toString(doubleArray));
[7.0, 9.0, 5.0, 1.0, 3.0 ]
int[] intArray = { 7, 9, 5, 1, 3 };
System.out.println(Arrays.toString(intArray));
[7, 9, 5, 1, 3 ]

This works for multi dimensional arrays too.

What if we have an array of strings, and want simple output; like: String[] array = {"John", "Mahta", "Sara"}, and we want this output without bracket and commas: John Mahta Sara?

FYI, Arrays.deepToString() accepts only an Object [] (or an array of classes that extend Object, such as Integer, so it won't work on a primitive array of type int []. But Arrays.toString(<int array>) works fine for primitive arrays.

Don't forget to import the Arrays library with import java.util.Arrays;

What's the simplest way to print a Java array? - Stack Overflow

java arrays printing
Rectangle 27 1745

Since Java 5 you can use Arrays.toString(arr) or Arrays.deepToString(arr) for arrays within arrays. Note that the Object[] version calls .toString() on each object in the array. The output is even decorated in the exact way you're asking.

String[] array = new String[] {"John", "Mary", "Bob"};
System.out.println(Arrays.toString(array));
[John, Mary, Bob]
String[][] deepArray = new String[][] {{"John", "Mary"}, {"Alice", "Bob"}};
System.out.println(Arrays.toString(deepArray));
//output: [[Ljava.lang.String;@106d69c, [Ljava.lang.String;@52e922]
System.out.println(Arrays.deepToString(deepArray));
[[John, Mary], [Alice, Bob]]
double[] doubleArray = { 7.0, 9.0, 5.0, 1.0, 3.0 };
System.out.println(Arrays.toString(doubleArray));
[7.0, 9.0, 5.0, 1.0, 3.0 ]
int[] intArray = { 7, 9, 5, 1, 3 };
System.out.println(Arrays.toString(intArray));
[7, 9, 5, 1, 3 ]

This works for multi dimensional arrays too.

What if we have an array of strings, and want simple output; like: String[] array = {"John", "Mahta", "Sara"}, and we want this output without bracket and commas: John Mahta Sara?

FYI, Arrays.deepToString() accepts only an Object [] (or an array of classes that extend Object, such as Integer, so it won't work on a primitive array of type int []. But Arrays.toString(<int array>) works fine for primitive arrays.

Don't forget to import the Arrays library with import java.util.Arrays;

What's the simplest way to print a Java array? - Stack Overflow

java arrays printing
Rectangle 27 40

first elements in decreasing order

Here's a complete example using Java 8:

import java.util.*;

public class Test {

    public static void main(String args[]) {

        int[][] twoDim = { {1, 2}, {3, 7}, {8, 9}, {4, 2}, {5, 3} };

        Arrays.sort(twoDim, Comparator.comparing((int[] arr) -> arr[0])
                                      .reversed());

        System.out.println(Arrays.deepToString(twoDim));
    }
}
[[8, 9], [5, 3], [4, 2], [3, 7], [1, 2]]

If you unfortunate enough to work on Java 6 or older, you'd do:

Arrays.sort(twoDim, new Comparator<int[]>() {
    @Override
    public int compare(int[] o1, int[] o2) {
        return ((Integer) o2[0]).compareTo(o1[0]);
    }
});

Sorry to bring up an old thread but why was there a need to cast to Integer when you return the compare method?

.compareTo
int

Oh gosh. Such small use case that have evolved in from 4, to 5, to 6, to 7, to 8 :-) Kind of interesting.

Java Comparator class to sort arrays - Stack Overflow

java arrays multidimensional-array comparator
Rectangle 27 25

Starting with Java 8, one could also take advantage of the join() method provided by the String class to print out array elements, without the brackets, and separated by a delimiter of choice (which is the space character for the example shown below):

String[] greeting = {"Hey", "there", "amigo!"};
String delimiter = " ";
String.join(delimiter, greeting)

What's the simplest way to print a Java array? - Stack Overflow

java arrays printing
Rectangle 27 23

Starting with Java 8, one could also take advantage of the join() method provided by the String class to print out array elements, without the brackets, and separated by a delimiter of choice (which is the space character for the example shown below):

String[] greeting = {"Hey", "there", "amigo!"};
String delimiter = " ";
String.join(delimiter, greeting)

What's the simplest way to print a Java array? - Stack Overflow

java arrays printing
Rectangle 27 22

Starting with Java 8, one could also take advantage of the join() method provided by the String class to print out array elements, without the brackets, and separated by a delimiter of choice (which is the space character for the example shown below):

String[] greeting = {"Hey", "there", "amigo!"};
String delimiter = " ";
String.join(delimiter, greeting)

What's the simplest way to print a Java array? - Stack Overflow

java arrays printing
Rectangle 27 170

Arrays are covariant, Generics are not:

You should not mix-up arrays and generics. They don't go well together. There are differences in how arrays and generic types enforce the type check. We say that arrays are reified, but generics are not. As a result of this, you see these differences working with arrays and generics.

What that means? You must be knowing by now that the following assignment is valid:

Basically, an Object[] is a super type of String[], because Object is a super type of String. This is not true with generics. So, the following declaration is not valid, and won't compile:

List<Object> list = new ArrayList<String>(); // Will not compile.

Generics were introduced in Java to enforce stronger type check at compile time. As such, generic types don't have any type information at runtime due to type erasure. So, a List<String> has a static type of List<String> but a dynamic type of List.

However, arrays carry with them the runtime type information of the component type. At runtime, arrays use Array Store check to check whether you are inserting elements compatible with actual array type. So, the following code:

Object[] arr = new String[10];
arr[0] = new Integer(10);

will compile fine, but will fail at runtime, as a result of ArrayStoreCheck. With generics, this is not possible, as the compiler will try to prevent the runtime exception by providing compile time check, by avoiding creation of reference like this, as shown above.

Consider the code as below:

Since the type of T is not known at runtime, the array created is actually an Object[]. So the above method at runtime will look like:

public Object[] getArray(int size) {
    Object[] arr = new Object[size];
    return arr;
}
Integer[] arr = getArray(10);

Here's the problem. You have just assigned an Object[] to a reference of Integer[]. The above code will compile fine, but will fail at runtime.

Now your last doubt, why the below code works:

E[] elements = (E[]) new Object[10];

The above code have the same implications as explained above. If you notice, the compiler would be giving you an Unchecked Cast Warning there, as you are typecasting to an array of unknown component type. That means, the cast may fail at runtime. For e.g, if you have that code in the above method:

public <T> T[] getArray(int size) {
    T[] arr = (T[])new Object[size];        
    return arr;
}
String[] arr = getArray(10);

this will fail at runtime with a ClassCastException. So, no this way will not work always.

The issue is the same. Due to type erasure, a List<String>[] is nothing but a List[]. So, had the creation of such arrays allowed, let's see what could happen:

List<String>[] strlistarr = new List<String>[10];  // Won't compile. but just consider it
Object[] objarr = strlistarr;    // this will be fine
objarr[0] = new ArrayList<Integer>(); // This should fail but succeeds.

Now the ArrayStoreCheck in the above case will succeed at runtime although that should have thrown an ArrayStoreException. That's because both List<String>[] and List<Integer>[] are compiled to List[] at runtime.

Yes. The reason being, a List<?> is a reifiable type. And that makes sense, as there is no type associated at all. So there is nothing to loose as a result of type erasure. So, it is perfectly type-safe to create an array of such type.

List<?>[] listArr = new List<?>[10];
listArr[0] = new ArrayList<String>();  // Fine.
listArr[1] = new ArrayList<Integer>(); // Fine

Both the above case is fine, because List<?> is super type of all the instantiation of the generic type List<E>. So, it won't issue an ArrayStoreException at runtime. The case is same with raw types array. As raw types are also reifiable types, you can create an array List[].

So, it goes like, you can only create an array of reifiable types, but not non-reifiable types. Note that, in all the above cases, declaration of array is fine, it's the creation of array with new operator, which gives issues. But, there is no point in declaring an array of those reference types, as they can't point to anything but null (Ignoring the unbounded types).

Yes, you can create the array using Array#newInstance() method:

public <E> E[] getArray(Class<E> clazz, int size) {
    @SuppressWarnings("unchecked")
    E[] arr = (E[]) Array.newInstance(clazz, size);

    return arr;
}

Typecast is needed because that method returns an Object. But you can be sure that it's a safe cast. So, you can even use @SuppressWarnings on that variable.

Nitpick: "Creation of array whose component type is ... a wildcard parameterized type, is type-unsafe." Actually instantiating e.g. a new List<?>[] { } is valid - it's just that the wildcard can't be bounded.

Also, "this will fail at runtime with a ClassCastException." is not exactly true. When a cast is unchecked it means that it won't fail fast. Instead, ClassCastExceptions may be thrown in other places, where the compiler has inserted casts during the process of erasure. This issue is a good example.

@PaulBellora. Actually, I meant bounded. Missed the word. Will edit thanks :)

@PaulBellora. As for casting part, I wrote that for casting to String[], that will certainly fail. Edited that part to make it clear.

java - How to create a generic array? - Stack Overflow

java generics
Rectangle 27 270

Always check the standard libraries first. Try:

System.out.println(Arrays.toString(array));

or if your array contains other arrays as elements:

System.out.println(Arrays.deepToString(array));

What if we have an array of strings, and want simple output; like: String[] array = {"John", "Mahta", "Sara"}, and we want this output without bracket and commas: John Mahta Sara?

@Hengameh Just store Arrays.toString(array) to a string variable and then remove the braces by replace method of Java

String.join(" ", Arrays.asList(array))

What's the simplest way to print a Java array? - Stack Overflow

java arrays printing
Rectangle 27 267

Always check the standard libraries first. Try:

System.out.println(Arrays.toString(array));

or if your array contains other arrays as elements:

System.out.println(Arrays.deepToString(array));

What if we have an array of strings, and want simple output; like: String[] array = {"John", "Mahta", "Sara"}, and we want this output without bracket and commas: John Mahta Sara?

@Hengameh Just store Arrays.toString(array) to a string variable and then remove the braces by replace method of Java

String.join(" ", Arrays.asList(array))

What's the simplest way to print a Java array? - Stack Overflow

java arrays printing
Rectangle 27 267

Always check the standard libraries first. Try:

System.out.println(Arrays.toString(array));

or if your array contains other arrays as elements:

System.out.println(Arrays.deepToString(array));

What if we have an array of strings, and want simple output; like: String[] array = {"John", "Mahta", "Sara"}, and we want this output without bracket and commas: John Mahta Sara?

@Hengameh Just store Arrays.toString(array) to a string variable and then remove the braces by replace method of Java

String.join(" ", Arrays.asList(array))

What's the simplest way to print a Java array? - Stack Overflow

java arrays printing
Rectangle 27 12

Examples: . . . In Java

Non-Nested Loops: . . . The Index is a value.

for (int i = 0; i < LOOP_LENGTH; i++) {

    // LOOP_BODY
}
for (int iRow = 0; iRow < ROWS; iRow++) {

    for (int iColumn = 0; iColumn < COLUMNS; iColumn++) {

        // LOOP_BODY
    }
}
foreach
Object
for (Object something : somethings) {

    // LOOP_BODY
}
for
iter
for (Iterator iter = collection.iterator(); iter.hasNext(); /* N/A */) {

    Object object = iter.next();

    // LOOP_BODY
}

while Loops: . . . Limit the scope of the Iterator.

/* LOOP_DESCRIPTION */ {

    Iterator iter = collection.iterator();

    while (iter.hasNext()) {

        // LOOP_BODY
    }
}

language agnostic - What is an ideal variable naming convention for lo...

language-agnostic naming-conventions
Rectangle 27 11

Example in Java

(?=\[)|(?<=\])

That is, anywhere where we assert a match of a literal [ ahead, or where we assert a match of literal ] behind.

As a C# string literal, this is

@"(?=\[)|(?<=\])"
System.out.println(java.util.Arrays.toString(
        "abc[s1]def[s2][s3]ghi".split("(?=\\[)|(?<=\\])")
    ));
    // prints "[abc, [s1], def, [s2], [s3], ghi]"

    System.out.println(java.util.Arrays.toString(
        "abc;def;ghi;".split("(?<=;)")
    ));
    // prints "[abc;, def;, ghi;]"

    System.out.println(java.util.Arrays.toString(
        "OhMyGod".split("(?=(?!^)[A-Z])")
    ));
    // prints "[Oh, My, God]"

c# - Regex split string but keep separators - Stack Overflow

c# regex split
Rectangle 27 11

Example in Java

(?=\[)|(?<=\])

That is, anywhere where we assert a match of a literal [ ahead, or where we assert a match of literal ] behind.

As a C# string literal, this is

@"(?=\[)|(?<=\])"
System.out.println(java.util.Arrays.toString(
        "abc[s1]def[s2][s3]ghi".split("(?=\\[)|(?<=\\])")
    ));
    // prints "[abc, [s1], def, [s2], [s3], ghi]"

    System.out.println(java.util.Arrays.toString(
        "abc;def;ghi;".split("(?<=;)")
    ));
    // prints "[abc;, def;, ghi;]"

    System.out.println(java.util.Arrays.toString(
        "OhMyGod".split("(?=(?!^)[A-Z])")
    ));
    // prints "[Oh, My, God]"

c# - Regex split string but keep separators - Stack Overflow

c# regex split
Rectangle 27 11

Example in Java

(?=\[)|(?<=\])

That is, anywhere where we assert a match of a literal [ ahead, or where we assert a match of literal ] behind.

As a C# string literal, this is

@"(?=\[)|(?<=\])"
System.out.println(java.util.Arrays.toString(
        "abc[s1]def[s2][s3]ghi".split("(?=\\[)|(?<=\\])")
    ));
    // prints "[abc, [s1], def, [s2], [s3], ghi]"

    System.out.println(java.util.Arrays.toString(
        "abc;def;ghi;".split("(?<=;)")
    ));
    // prints "[abc;, def;, ghi;]"

    System.out.println(java.util.Arrays.toString(
        "OhMyGod".split("(?=(?!^)[A-Z])")
    ));
    // prints "[Oh, My, God]"

c# - Regex split string but keep separators - Stack Overflow

c# regex split
Rectangle 27 11

Example in Java

(?=\[)|(?<=\])

That is, anywhere where we assert a match of a literal [ ahead, or where we assert a match of literal ] behind.

As a C# string literal, this is

@"(?=\[)|(?<=\])"
System.out.println(java.util.Arrays.toString(
        "abc[s1]def[s2][s3]ghi".split("(?=\\[)|(?<=\\])")
    ));
    // prints "[abc, [s1], def, [s2], [s3], ghi]"

    System.out.println(java.util.Arrays.toString(
        "abc;def;ghi;".split("(?<=;)")
    ));
    // prints "[abc;, def;, ghi;]"

    System.out.println(java.util.Arrays.toString(
        "OhMyGod".split("(?=(?!^)[A-Z])")
    ));
    // prints "[Oh, My, God]"

c# - Regex split string but keep separators - Stack Overflow

c# regex split
Rectangle 27 52

Arrays are in fact objects, so a reference is passed (the reference itself is passed by value, confused yet?). Quick example:

You will see the changes to the list from the calling code. However you can't change the reference itself, since it's passed by value:

// assuming you allocated the list
public void changeArray(Integer[] list) {
    list = null;
}

If you pass a non-null list, it won't be null by the time the method returns.

No, everything is passed by value in Java ! Passing by reference doesn't exist in JAva, as it doesn't exist in ANSI C, thats why pointers exist ...

@aleroot: I said a reference is passed to the method, otherwise you couldn't see changes, not that java is pass-by-reference! Yes, the reference is passed by values, but that's not the point.

@Tudor your sentence is not clear ...

Are arrays passed by value or passed by reference in Java? - Stack Ove...

java arrays
Rectangle 27 74

This is nice to know, however, as for "always check the standard libraries first" I'd never have stumbled upon the trick of Arrays.toString( myarray )

--since I was concentrating on the type of myarray to see how to do this. I didn't want to have to iterate through the thing: I wanted an easy call to make it come out similar to what I see in the Eclipse debugger and myarray.toString() just wasn't doing it.

import java.util.Arrays;
.
.
.
System.out.println( Arrays.toString( myarray ) );

What if we have an array of strings, and want simple output; like: String[] array = {"John", "Mahta", "Sara"}, and we want this output without bracket and commas: John Mahta Sara?

@Hengameh I think that's another topic. You can manipulate this String with the common string operations afterwards... Like Arrays.toString(myarray).replace("[", "("); and so on.

What's the simplest way to print a Java array? - Stack Overflow

java arrays printing
Rectangle 27 73

This is nice to know, however, as for "always check the standard libraries first" I'd never have stumbled upon the trick of Arrays.toString( myarray )

--since I was concentrating on the type of myarray to see how to do this. I didn't want to have to iterate through the thing: I wanted an easy call to make it come out similar to what I see in the Eclipse debugger and myarray.toString() just wasn't doing it.

import java.util.Arrays;
.
.
.
System.out.println( Arrays.toString( myarray ) );

What if we have an array of strings, and want simple output; like: String[] array = {"John", "Mahta", "Sara"}, and we want this output without bracket and commas: John Mahta Sara?

@Hengameh I think that's another topic. You can manipulate this String with the common string operations afterwards... Like Arrays.toString(myarray).replace("[", "("); and so on.

What's the simplest way to print a Java array? - Stack Overflow

java arrays printing