1

Why does this work

public E a;
public MySortedArray(E asdf){
    a = asdf;
}

and this doesn't?

public E[] a;
public MySortedArray(E[] asdf){
    a = asdf;
}

How can I achieve the second when let's say I do

    MySortedArray<Integer> test = new MySortedArray<>(integersArray);
6
  • 1
    What is integersArray? A Integer[]? A int[]? Commented Nov 12, 2014 at 19:35
  • See Restrictions on Generics in the Java Tutorial. For the second, you should use List<E> instead of E[] and use the List API instead of array subscripting. Commented Nov 12, 2014 at 19:38
  • @TedHopp I don't think that this involves the creation of a generic array as in your "duplicate of"; just the passing of an array to a generic class. Commented Nov 12, 2014 at 19:40
  • @TedHopp I thought as well, but we are restricted from doing so. Commented Nov 12, 2014 at 19:42
  • 1
    I have voted to re-open the question. Commented Nov 12, 2014 at 19:44

1 Answer 1

2

Java does support boxing int to Integer, but not boxing arrays of those numeric types, e.g. it won't box int[] to Integer[].

You must convert the int[] to an Integer[] yourself before passing it to your MySortedArray<Integer> instance.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks! I still need to practice on Generics, as I always avoided them even in advanced projects.
May the ? extends Force be with you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.