キーを使用してHashMapの値を更新するJavaプログラム
この記事では、キーを使用してHashMapの値を更新する方法を理解します。 Java HashMapは、JavaのMapインターフェースのハッシュテーブルベースの実装です。これは、キーと値のペアのコレクションです。
以下は同じのデモンストレーションです-
入力がであると仮定します −
Input HashMap: {Java=1, Scala=2, Python=3} 必要な出力は −
The HashMap with the updated value is: {Java=1, Scala=12, Python=3} アルゴリズム
Step 1 - START Step 2 - Declare namely Step 3 - Define the values. Step 4 – Create a hashmap of values and initialize elements in it using the ‘put’ method. Step 5 - Display the hashmap on the console. Step 6 - To fetch a specific value, access the hashmap using the key, with the ‘get’ method. Step 7 - Add certain value to the fetched value. Step 8 - Display the updated value on the console. Step 9 - Stop
例1
ここでは、「main」関数の下ですべての操作をバインドします。
import java.util.HashMap;
public class Demo {
public static void main(String[] args) {
System.out.println("The required packages have been imported");
HashMap<String, Integer> input_map = new HashMap<>();
input_map.put("Java", 1);
input_map.put("Scala", 2);
input_map.put("Python", 3);
System.out.println("The HashMap is defined as: " + input_map);
int value = input_map.get("Scala");
value = value + 10;
input_map.put("Scala", value);
System.out.println("\nThe HashMap with the updated value is: " + input_map);
}
} 出力
The required packages have been imported
The HashMap is defined as: {Java=1, Scala=2, Python=3}
The HashMap with the updated value is: {Java=1, Scala=12, Python=3} 例2
ここでは、操作をオブジェクト指向プログラミングを示す関数にカプセル化します。
import java.util.HashMap;
class Demo {
static void update(HashMap<String, Integer> input_map, String update_string){
int value = input_map.get(update_string);
value = value + 10;
input_map.put("Scala", value);
System.out.println("\nThe HashMap with the updated value is: " + input_map);
}
public static void main(String[] args) {
System.out.println("The required packages have been imported");
HashMap<String, Integer> input_map = new HashMap<>();
input_map.put("Java", 1);
input_map.put("Scala", 2);
input_map.put("Python", 3);
System.out.println("The HashMap is defined as: " + input_map);
String update_string = "Scala";
update(input_map, update_string);
}
} 出力
The required packages have been imported
The HashMap is defined as: {Java=1, Scala=2, Python=3}
The HashMap with the updated value is: {Java=1, Scala=12, Python=3} -
JavaでのHashMapの内部動作
関数「hashCode」は、Javaでオブジェクトのハッシュコードを取得するために使用されます。これはスーパークラスObjectのオブジェクトです。オブジェクト参照のメモリを整数として返します。これはネイティブ関数です。つまり、Javaの直接メソッドを使用してオブジェクトの参照をフェッチすることはできません。 HashMapのパフォーマンスを向上させるには、hashCode()を適切に使用してください。基本的に、この関数はバケット値とインデックス値を計算するために使用されます。次のように定義されます- public native hashCode() 「バケット」について説明したので、それ
-
コマンドプロンプトを使用してJavaプログラムをコンパイルして実行するにはどうすればよいですか?
多くのプログラミング環境では、環境内でプログラムをコンパイルして実行できますが、コマンドプロンプトを使用してJavaプログラムをコンパイルして実行することもできます。 システムにJDKが正常にインストールされ、パスが設定されると、コマンドプロンプトを使用してJavaプログラムをコンパイルおよび実行できるようになります。 ステップ1-メモ帳または他のIDEのいずれかでJavaプログラムを作成する必要があります。 ステップ2-このJavaファイルを「Demo.java」のあるフォルダに保存する必要があります そしてそれはフォルダに保存することができます。 ステップ3-JAVACを使用してコマン