Wątek przeniesiony 2015-12-18 18:20 z Java przez bogdans.

HashMap wstawianie w funkcji

0

Witam

Próbuje napisać funkcję w klasie Set, która ma za zadanie wstawiać klucz i wartość zadeklarowane wcześniej w klasie Para. Coś mi nie pasuje w tym wszystkim, podejrzewam że w złym miejscu umieszczam HashMap i tworze obiekt klasy Para. Próbowałem już to przemieszczać w różne miejsca i zawsze jest źle. Poza tym w tym miejscu hash.put(kl, Para.setValue(wart)); zamiast kl chciałbym wstawić odniesienie do key klasy Para, bo po to je właśnie tworzyłem, ale żadnym sposobem nie da się tego zrobić, nie da się nawet ustawić gettera i settera dla tego pola. Czy ktoś wie co można zrobić żeby to lepiej działało?

import java.util.HashMap;

public class Para {
public final String key;
private int value;

public int getValue()
{
    return this.value;
}

public void setValue(int value)
{
     this.value = value;
}

}

public class Set {
	static HashMap<String, Integer> hash = new HashMap<>();
	public static void wstaw (String kl, int wart) {
		Para para = new Para();
		hash.put(kl, Para.setValue(wart));
		System.out.print((Integer)hash.get(kl));}
}

public class Main {

	public static void main(String[] args) {
		Set zbior = new Set();
		zbior.wstaw("something", 2);

	}

}

Błędy jakie się pojawiają to:

The public type Para must be defined in its own file The public type Set must be defined in its own file The method put(String, Integer) in the type HashMap<String,Integer> is not applicable for the arguments
(String, void)
Cannot make a static reference to the non-static method setValue(int) from the type Para

1

No te komunikaty błędów nie mogą być bardziej czytelne.

The public type Para must be defined in its own file

Stwórz plik Para.java i tam wrzuć klasę Para. W Javie klasy publiczne muszą być w pliku o takiej samej nazwie.

The public type Set must be defined in its own file

Jw.

The method put(String, Integer) in the type HashMap<string,integer> is not applicable for the arguments
(String, void)

Metoda setValue w klasie Para nic nie zwraca - stąd nie da się wrzucić niczego do HashMapy. Stwórz wyrażenie, które ma typ integer a nie void.

Cannot make a static reference to the non-static method setValue(int) from the type Para

Metoda setValue jest metodą instancji, potrzebujesz instancji do jej wywołania. Jeśli jesteś w metodzie niestatycznej w klasie Para to możesz użyć this (którego nie trzeba i zwykle się explicite nie wpisuje). W każdym innym przypadku potrzebujesz referencji do obiektu typu Para (np para.getValue()), by wywołać na nim niestatyczną metodę.

1 użytkowników online, w tym zalogowanych: 0, gości: 1