JAVA Dictionary as parameter [duplicate] - java

This question already has answers here:
What does it mean to "program to an interface"?
(33 answers)
Closed 3 years ago.
Now I got a dictionary like this
Dictionary dict = new Hashtable();
dict.put("shipno", item.getShipNumber());
dict.put("addr", item.getFinalAddr());
dict.put("receiver", item.getReceiverName());
dict.put("phone", item.getReceiverPhone());
and I'm going to pass this dictionary to funcion Test() as a parameter, what should I put in the '()'
public static int Test(Dictionary)
Is this correct? Thanks!

In your code you have to call this method:
Dictionary dict = new Hashtable();
dict.put("shipno", item.getShipNumber());
// CAll THIS METHOD
Test(dict);
And in your method you can get this data:
// YOUR METHOD, where "dict" is passed argument/parameter
public static int Test(Dictionary dict) {
}

Its working here
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.Hashtable;
public class Dict {
public static void main(String[] args) {
Dictionary<String, String> obj = new Hashtable<String, String>();
obj.put("Hello", "World");
obj.put("Hello1", "World3");
obj.put("Hello2", "World32");
Dict ca = new Dict();
ca.test(obj);
}
public void test(Dictionary<String, String> obj) {
Enumeration<String> enumData = obj.elements();
while (enumData.hasMoreElements()) {
System.out.println(enumData.nextElement());
}
}
}

Related

Java: refer to a class variable using a variable [duplicate]

This question already has answers here:
Java: How can I access a class's field by a name stored in a variable?
(2 answers)
Closed 4 years ago.
File Lists_of_values.java:
public class Lists_of_values {
public static List<String> circumstances = new ArrayList<String>(Arrays.asList("Medical", "Maternity", "Bereavement", "Other"));
public static List<String> interruptions = new ArrayList<String>(Arrays.asList("Awaiting results", "Courses not available", "Fieldwork",
"Health reasons", "Internship with stipend", "Other"));
}
File Main_file.java:
public String getDropdownValues(String lovs) {
String templovList = StringUtils.join(Lists_of_values.lovs, ' ');
return templovList;
}
This is giving me: lovs cannot be resolved or is not a field
Is there a way to use a variable in this context as a parameter in getDropdownValues? So that I can just call getDropdownValues("circumstances").
You could also introduce a Map that holds a reference based on the name:
import java.util.*;
public class Lists_of_values {
public static List<String> circumstances = Arrays.asList("Medical", "Maternity", "Bereavement", "Other");
public static List<String> interruptions = Arrays.asList("Awaiting results", "Courses not available", "Fieldwork", "Health reasons", "Internship with stipend", "Other");
private static Map<String, List<String>> lists = new HashMap<>();
static {
lists.put("circumstances", circumstances);
lists.put("interruptions", interruptions);
}
public static List<String> getList(String name) {
return lists.get(name);
}
}
That would be used as: List_of_Values.getList("circumstances")
This would also allow your code to be obfuscated, which would break if you decide to use reflection.
No, you cannot (Unless you resort to reflection APIs)
A right way would be to pass the appropriate list to getDropdownValues
public String getDropdownValues(List<String> list) {
String templovList = StringUtils.join(list, ' ');
return templovList;
}
Call it as
getDropdownValues(circumstances); //or getDropdownValues(interruptions);

Core java basics [duplicate]

This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 4 years ago.
How can I update the only str2 by not really updating str1 and str? Why is the change in str2 is updating str1 and str? Is it because of the object reference?
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class test {
List<HashMap<String, String>> str;
public static void main(String[] args) {
Map<String, String> hmap = new HashMap<String, String>();
hmap.put("1", "s1");
hmap.put("2", "s2");
test testobj = new test();
testobj.str = new ArrayList<HashMap<String, String>>();
testobj.str.add((HashMap<String, String>) hmap);
testing(testobj.str);
}
static void testing(List<HashMap<String, String>> str) {
List<HashMap<String, String>> str2 = new ArrayList<HashMap<String, String>>();
List<HashMap<String, String>> str1 = str;
str2.add(str1.get(0));
str2.get(0).put("1", "new");
System.out.println(str);
System.out.println(str1);
System.out.println(str2);
}
}
You have to create a copy of the original List like this:
List<HashMap<String, String>> str1 = new ArrayList<>(str);
which creates a new ArrayList containing all the elements from the original List. This way you'll have two separate list containing its own elements.

How do I print out all keys in hashmap? [duplicate]

This question already has answers here:
Printing HashMap In Java
(17 answers)
Closed 8 years ago.
I'm trying to learn how hashmaps work and I've been fiddling with a small phonebook program.
But I'm stumped at what to do when I want to print out all the keys.
here's my code:
import java.util.HashMap;
import java.util.*;
public class MapTester
{
private HashMap<String, String> phoneBook;
public MapTester(){
phoneBook = new HashMap<String, String>();
}
public void enterNumber(String name, String number){
phoneBook.put(name, number);
}
public void printAll(){
//This is where I want to print all. I've been trying with iterator and foreach, but I can't get em to work
}
public void lookUpNumber(String name){
System.out.println(phoneBook.get(name));
}
}
Here we go:
System.out.println(phoneBook.keySet());
This will printout the set of keys in your Map using Set.toString() method. for example :
["a","b"]
You need to get the keySet from your hashMap and iterate it using e.g. a foreach loop. This way you're getting the keys which can then be used to get the values out of the map.
import java.util.*;
public class MapTester
{
private HashMap<String, String> phoneBook;
public MapTester()
{
phoneBook = new HashMap<String, String>();
}
public void enterNumber(String name, String number)
{
phoneBook.put(name, number);
}
public void printAll()
{
for (String variableName : phoneBook.keySet())
{
String variableKey = variableName;
String variableValue = phoneBook.get(variableName);
System.out.println("Name: " + variableKey);
System.out.println("Number: " + variableValue);
}
}
public void lookUpNumber(String name)
{
System.out.println(phoneBook.get(name));
}
public static void main(String[] args)
{
MapTester tester = new MapTester();
tester.enterNumber("A name", "A number");
tester.enterNumber("Another name", "Another number");
tester.printAll();
}
}
Maps have a method called KeySet with all the keys.
Set<K> keySet();

How to input the objects to a ArrayList <HashMap<String,Object>>

I have 1 object(Goods) have 2 attributes: String and boolean. How to input object Goods to ArrayList<HashMap<String, Object>> ? Because I want input ArrayList<HashMap<String, Object>> to SimpleAdapter
public class Goods {
private String goodsName;
private boolean isCheck = false;
public String getGoodsName() {
return goodsName;
}
public void setGoodsName(String goodsName) {
this.goodsName = goodsName;
}
public boolean isCheck() {
return isCheck;
}
public void setCheck(boolean isCheck) {
this.isCheck = isCheck;
}
}
package ngo;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Goods g = new Goods();
g.setGoodsName("foo");
g.setCheck(true);
Map<String, Goods> map = new HashMap<String, Goods>();
map.put(g.getGoodsName(), g);
List<Map<String, Goods>> list = new ArrayList<Map<String, Goods>>();
list.add(map);
System.out.println(list.get(0).get("foo").isCheck());
}
}
Displays true
This should be an acceptable, if simple, structure for the data parameter of SimpleAdapter's constructor. A more exhaustive example of it's use can be found here
The following is the basic example, not runnable in itself.
ArrayList<HashMap<String, Goods>> listOfMappedGoods = new ArrayList<HashMap<String, Goods>>();
HashMap<String, Goods> goodsList = new HashMap<String, Goods>();
Goods g = new Goods();
g.setGoodsName("foo");
g.setCheck(true);
goodsList.add(g.getGoodsName(), g);
listOfMappedGoods.add(goodsList);
The point to note, is that just like every new Goods object needs to be created using new Goods(), each new goodsList needs to be created also using new HashMap<String, Goods>().
If you use something like goodsList.clear(), then you are still referring to the original map that was first added to the listOfMappedGoods, so you will clear that instead.

How to convert a String[] into a set? [duplicate]

This question already has answers here:
Java: How to convert String[] to List or Set [duplicate]
(9 answers)
Closed 9 years ago.
I did this:
Set<String> mySet = new TreeSet<String>();
String list = ("word,another,word2"); // actually this is much bigger
String[] wordArr = list.split(",");
mySet.addAll(wordArr);
This gives error:
The method addAll(Collection<? extends String>) in the type Set<String> is
not applicable for the arguments (String[])
I think my intentions are clear.
Side ques: is there a better way to achieve my desired set? I know already there are no repeated value in my list.
The TreeSet constructor accepts a Collection, a String[] can be converted to a List which implements Collection using Arrays.asList().
public static void main(String[] args) {
String list = "word,another,word2"; //No need for () here
String[] wordArr = list.split(",");
Set<String> mySet = new TreeSet<String>(Arrays.asList(wordArr));
for(String s:mySet){
System.out.println(s);
}
}
Here's an example using Guava:
package com.sandbox;
import com.google.common.collect.Sets;
import java.util.Set;
public class Sandbox {
public static void main(String[] args) {
String list = ("word,another,word2"); // actually this is much bigger
String[] wordArr = list.split(",");
Set<String> mySet = Sets.newHashSet(wordArr);
}
}
If you want to do this without Arrays (I don't recommend, but you're in a class so maybe you can't use it):
package com.sandbox;
import java.util.Set;
import java.util.TreeSet;
public class Sandbox {
public static void main(String[] args) {
Set<String> mySet = new TreeSet<String>();
String list = ("word,another,word2"); // actually this is much bigger
String[] wordArr = list.split(",");
for (String s : wordArr) {
mySet.add(s);
}
}
}

Categories