unable to use constructor in java [duplicate] - java

This question already has answers here:
java generics: can't create a simple print array method
(2 answers)
Closed 2 years ago.
I have started learing java generics and this is my priority queue implementation:
public class MinPQ<Key> implements Iterable<Key> {
private Key[] pq; // store items at indices 1 to n
private int n; // number of items on priority queue
private Comparator<Key> comparator; // optional comparator
public MinPQ(Key[] keys) {
n = keys.length;
pq = (Key[]) new Object[keys.length + 1];
.....
.....
}
}
And this is my main class :
public class Demo {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] ar = {1,2,3};
MinPQ<Integer> pq = new MinPQ<Integer>(ar);
}
}
But here I get an error stating "The constructor MinPQ(int[]) is undefined" can someone please help me find the issue here ?

You can't use primitive types with generics. Just change:
int[] ar = {1,2,3};
to:
Integer[] ar = {1,2,3};
or box it with
IntStream.of(ar).boxed().toArray(Integer[]::new)
Basically you're trying to pass an int[] to a constructor which requires Integer[], because of MinPQ<Integer> declaration. So, in tehory it should work if you declared it as MinPQ<int> - but as stated at the beginning we can't use primitive types for generics.

Related

java Cannot resolve method 'contains(int)'

This code block prints "not contains" and i don't know why, can somebody help me ?
private static final int[] YEARS = new int[] {
1881, 1893, 1900, 1910, 1919, 1923, 1930, 1932, 1934, 1938
};
public static void main(String[] args) {
int year = 1919;
System.out.println(YEARS);
if (Arrays.asList(YEARS).contains(year))
{
System.out.println("Contains");
}
else {
System.out.println("Not contains");
}
// Write your code here below
}
}
Arrays.asList(YEARS) will result in a List<int[]>, you will not find a single int in there using the contains(int) method of a List…
You probably expected a List<Integer>, which you can get by
List<Integer> years = Arrays.stream(YEARS).boxed().collect(Collectors.toList());
The resulting List<Integer> can be checked for the presence of a single int using the contains method because it is a list of integers contrary to the list of arrays of integers produced by Arrays.asList(YEARS).
that's because you are using int
in your arraylist when you should be using Integer
int is a primitive type and doesn't work with Arraylist which requires a non-primitive type
change int to Integer and that code should work

Why is my List modified when I alter the array it was created from [duplicate]

This question already has an answer here:
List values change if I change the array passed to Arrays.asList(array)
(1 answer)
Closed 3 years ago.
import java.util.*;
public class Test {
public static void main(String[] args) {
String[] arr = {"Java", "Champ", "."};
List<String> list = (List<String>) Arrays.asList(arr); // line 1
arr[2] = ".com"; // line 2
for (String word : list) {
System.out.print(word);
}
}
}
Can please someone explain me why we get here "JavaChamp.com"?
I thought it shoud be just "JavaChamp." because line 2 after line 1.
Because Arrays#asList returns the fixed-size List backed by the array.
Here is the doc of Arrays#asList:
Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.) This method acts as bridge between array-based and collection-based APIs, in combination with Collection.toArray(). The returned list is serializable and implements RandomAccess.
You can actually take a look at the code if you want to understand what's happening. In your case, let's take a look at java.util.Arrays#asList(T...)
#SafeVarargs
public static <T> List<T> asList(T... var0) {
return new Arrays.ArrayList(var0); // notice this
}
It returns an inner class called 'ArrayList' (not to be confused with java.util.ArrayList, these are different classes, but they do more or less the same thing).
// the inner class
private static class ArrayList<E> extends AbstractList<E> implements RandomAccess, Serializable {
private final E[] a;
ArrayList(E[] var1) {
this.a = Objects.requireNonNull(var1); // directly reuses the array you pass in
}
}
Based on this code, we see that the array is reused. It's also important to note that Java will pass arrays as is rather than as a copy in parameters. What does that mean?
int[] arr = { 1, 2, 3, 4, 5 };
modifyArray(arr);
assert arr[0] == 2; // true
void modifyArray(int[] array) {
array[0] = 2;
}
Due to this, we can confirm we will share the array instance across parameters. For that reason, when you mutate the array from your scope, you are indirectly affecting the backing array for Arrays$ArrayList.

Java class with method that accepts list of any object [duplicate]

This question already has answers here:
What is the reason behind "non-static method cannot be referenced from a static context"? [duplicate]
(13 answers)
Closed 5 years ago.
I want to create a class that can be made without any parameters, and has a method that takes a list of any object and behaves like this:
List<String> list1 = Arrays.asList(new String [] {"a","b"});
List<String> result1 = myClass.myMethod(list1);
List<Integer> list2 = Arrays.asList(new String [] {1,2});
List<Integer> result1 = myClass.myMethod(list2);
Here's my attempt after reading briefly about Java generics:
public class myClass<T> {
public List<T> myMethod(List<T> input) {
...
return input; // just an example
}
Why doesn't this work?
I think the problem is that you put the parameter on the class, but really only need it on the method. Try:
public class MyClass {
// this is a parameterized method
public static <T> List<T> myMethod(List<T> input) {
...
return input; // just an example
}
}

unable to printout arrayOfInt initialised within the class constructor [duplicate]

This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 7 years ago.
I'm new to Java and is trying to learn the concept of constructor. I tried to print out the value of arrayOfInts in the main method using (to test whether the constructor was initialised the way I expected)
System.out.println(ds.arrayOfInts);
However, instead of printing out the values, the output is:
[I#15db9742
Why am I getting the wrong result and how I can print out the correct result? (i.e. the value stored in arrayOfInts).
public class DataStructure {
public static void main(String[] args) {
DataStructure ds = new DataStructure();
//System.out.println(ds.arrayOfInts); Doesnt work as expected
}
private final static int SIZE = 15;
private int[] arrayOfInts = new int[SIZE];
public DataStructure() {
int arrayValue = 0;
for (int i = 0; i < SIZE; i++) {
arrayOfInts[i] = ++arrayValue;
}
}
}
You are trying to print an array. An array is an object.
In order to display it correctly, you can loop through it, or use the Arrays.toString() method:
System.out.println(Arrays.toString(ds.arrayOfInts));
which returns a string representation of the specified array.
Arrays are objects in java. You need to iterate over elements and print them. Here is a sample implementation using the for-each loop.
public void print() {
for (int x : arrayOfInts) {
System.out.println(x);
}
}

HashTable generic array creation error [duplicate]

This question already has answers here:
How to create a generic array in Java?
(32 answers)
Closed 9 years ago.
This is a grade 12 java HashTable assignment.
So my teacher gave me the template for doing this assignment, but it does not work :(. And he expects us to get the template to work and then do the assignment.
Here's what he gave us:
class MyHashTable<T>{
private T[] vals;
private int load;
public MyHashTable(){
load = 0;
vals = new T[10];
}
public MyHashTable(int size){
load = 0;
vals = new T[size];
}
public void add(T obj){//don't care about negatives
int size = vals.length;
if((load+1.0)/size>0.6){
size*=10;
T[] tmp = new T[size];
for(int i=0;i<size/10;i++){
if(vals[i]!=null){
add(vals[i], tmp);
}
}
vals = tmp;
}
add(obj, vals);
}
public void add(T obj, T[]vals){
int loc = Math.abs(obj.hashCode())%vals.length;
while(vals[loc]!=null){
loc = (loc+1)%vals.length;
}
vals[loc] = obj;
}
/*public boolean contains(T obj){
} */
}
it gives an error: error: generic array creation
Can anyone tell me what does that mean? With examples hopefully.
Due to the way that generics are implemented in Java, it is not possible to use generics such that type information is needed at runtime. See this.
error: generic array creation
You can not create arrays from generic types.
See also What's the reason I can't create generic array types in Java?
As everybody said generic type is erased at runtime:
T becomes Object,
T extends SomeClass becomes SomeClass.
So you have at least two options
You can use same pattern that was used in ArrayList<T> and store items in Object[] array rather then T[] array
vals = (T[]) new Object[size];
If you want to create array of real T type you would have to make user to pass instance of Class<T> object that will correspond T and use it like
vals = (T[]) java.lang.reflect.Array.newInstance(clazzT, size);
where clazzT is Class<T> instance.

Categories