how can I see or get data from bucket in HashMap? - collections

I want to clarify for myself how HashMap works. I created a Person object with an invalid hash code.
So I created a HashMap<Person, Integer> and put in some data.
I want to see how my nodes lie in the same bucket.
How can I see it? Where can I do it?
HashMap<Person, Integer> hm = new HashMap<>();
Person a = new Person(1);
Person b = new Person(1);
Person c = new Person(2);
hm.put(a, 20);
hm.put(b, 20);
hm.put(c, 100);
hm.put(b, 15);
I have read this https://stackoverflow.com/questions/28346818/how-to-get-all-element-of-a-bucket-in-hashmap but there is only information that I can see this with a debugger but I have not found a method or way how I can do this

Related

JavaFX ComboBox readFromFile

In JavaFX is it at all possible to fill a ComboBox with items read from a file? Basically, I have a list of all the street names in a country and I want to display them within my ComboBox as options. Thanks.
Edit:
Finally found some time to actually tackle however I got stuck when it came to loading the array into the combobox. Any help?
This is the method which reads from the file:
private String ReadTownsAndCities(String[] choice){
List<String> list = new ArrayList<>();
String s;
FileReader fr;
BufferedReader br;
try{
fr = new FileReader("TownsAndCities.txt");
br = new BufferedReader(fr);
while((s = br.readLine()) !=null){
list.add(s);
}
choice = list.toArray(new String[list.size()]);
fr.close();
}catch(FileNotFoundException exc){
System.out.println("Cannot open input file.");
}catch(IOException exc){
System.out.println("Error reading file");
}
Now I need to load it into this combobox:
//locality combo box
localityCombo = new ComboBox<>();
//localityCombo.getItems().addAll();
grid.add(localityCombo, 1,11);
Depends on what format does the file have. If it contains many lines and each line is a street name, i would read the file line by line with a WHILE-Loop and for each iteration create a new Item in your ComboBox.

Update operation in DynamoDB

Here is a question raised during our data structure design. Currently, we have a data as the following:
class {
private String id;
private Map<String, Object> map;
...
}
We will have an operation to add new entries to the map frequently. I am wondering whether the data needs to be fetched from DynamoDB first, add new entries to the map and do a DB update with the modified data or not? (That is how Mongo update works.) If not, the data structure design isn't good.
Yes, you need to fetch the data from DynamoDB first and then add a new entry to map and save the object.
If the object is of type List, then you can append values to the existing list.
List<String> nameList = new ArrayList<>();
nameList.add("1");
UpdateItemSpec updateItemSpec = new UpdateItemSpec().withPrimaryKey("Id", testId).withReturnValues(ReturnValue.ALL_NEW).withUpdateExpression("set #Names = list_append (#Names, :val1)").withNameMap(new NameMap().with("#Names", "Names"))
.withValueMap(new ValueMap().withList(":val1", nameList));
UpdateItemOutcome outcome = table.updateItem(updateItemSpec);

Fragment showing Old Data

I am new to android programming. I am implementing functionality to scan particular Inventory Item and search for the barcode if it already exists in an ArrayList. If it exists then I am replacing the current Scan fragment with the InvnetoryFound Fragment in which I have option to update quantity and completely remove item from ArrayList.
The issue I am facing is, after removing Inventory when I scan again for different Inventory barcode, upon successful scan, it is showing InventoryFound Fragment with old data that was removed from ArrayList. Below is my code:
Test ArrayList Code:
public static String[] inve = new String[5];
public static ArrayList<String[]> inventory_list = new ArrayList<String[]>();
inve[0] = "INV45879";
inve[1] = "Bridge Support Pipe";
inve[2] = "Pre-insulated pipe supports provide both support and insulation in hot and cold piping applications.Pre-insulated pipe supports provide both support and insulation in hot and cold piping applications.";
inve[3] = "0885370720679";
inve[4] = "2";
inventory_list.add(inve);
inve = new String[5];
inve[0] = "INV45880";
inve[1] = "Cement";
inve[2] = "Pre-insulated pipe supports provide both support and insulation in hot and cold piping applications";
inve[3] = "9771234567003";
inve[4] = "8";
inventory_list.add(inve);
If scan is successful it calls below function to replace fragment:
private static void showFragment(Fragment fragment, String back_option) {
try {
// start transition
FragmentTransaction ft = activity.getFragmentManager().beginTransaction();
//if fragment Inventory is found then pass data to fragment
if(back_option.equals("inventoryFound")){
//sends found inventory list data to fragment
String[] inv_data = inventory_list.get(inventory_index);
Bundle bundle = new Bundle();
bundle.putStringArray("inventory_data",inv_data);
bundle.putInt("inventory_index",inventory_index);
inventoryFoundFragment.setArguments(bundle);
back_option = "null";
// replace fragment
if (!back_option.equals("null")) // with back option
ft.replace(R.id.frag_content, fragment).addToBackStack(back_option);
else // no back option
ft.replace(R.id.frag_content, fragment);
// commit
ft.commit();
}
catch(Exception e){
out("PROBLEM SHOWING FRAGMENT!!!"+e.getMessage());
}
}
InventoryFound fragment populates data and works fine. Below is the code when I click on Remove populated Inventory:
public void removeInventory(){
Shared.inventory_list.remove(inventory_index);
Toast.makeText(mContext,"Inventory "+inventory_index+" Removed Successfully!", Toast.LENGTH_SHORT).show();
FragmentTransaction ft = getActivity().getFragmentManager().beginTransaction();
ft.remove(this);
ft.replace(R.id.frag_content, new ScanFragment());
ft.commit();
}
It is removing successfully but when I scan it again e.g. for barcode "0885370720679" it shows the previous data on InventoryFound fragment. I have debugged it in Logcat (Log.d) and I am able to see correct data but it is not displaying in fragment.
any suggestions or guidance will be appreciated.
I found the solution for this problem.
When Fragment is in foreground, it calls onResume() method. In this method I call user-defined function which re-sets the data for Fragment fields. I don't know if it's a correct to way to fix this issue but it's working for me now!

How can I clear all data in a JavaFX graph?

I get this weird exception and I think that it is a bug. I am trying to clear a Series, which contains a list of points to plot in the graph. However, after clearing I want to add new Data and this gives me a nul pointer exception. My code:
public static void main(String[] args) {
Series<String, Number> series = new Series<String, Number>();
Number value1 = new Integer(5);
Number value2 = new Integer(6);
Data<String, Number> point1 = new Data<String, Number>("Something", value1);
Data<String, Number> point2 = new Data<String, Number>("Something", value2);
series.getData().add(point1);
series.getData().add(point2);
series.getData().clear();
Number value3 = new Integer(7);
Data<String, Number> point3 = new Data<String, Number>("Something", value3);
**series.getData().add(point3);**
}
I get a null pointer exception at the marked code line. I just need a way to reset this series, but to me it seems like a bug in JavaFX. I use Java 8, which has JavaFX as an integration.
Can someone help me?
The technical reason is a NPE in the listener on the data list, installed by series:
if (c.getAddedSize() > 0) {
for (Data<X,Y> itemPtr = begin; itemPtr != null; itemPtr = itemPtr.next) {
if (itemPtr.setToRemove) {
getChart().dataBeingRemovedIsAdded(itemPtr, Series.this);
itemPtr.setToRemove = false;
}
}
}
This will throw on the next addition if an item had been deleted while the chart is null.
The deeper reason is the slightly convoluted delete mechanism: the series doesn't delete the item itself but only marks it as ready for deletion. Then it delegates the change to its chart which then calls back into the series to do the actual delete. And that mechanism breaks if there is no chart.
Real solutions might be hard from the outside, because everything is so tightly and secretly knitted - no way to hook your own listener to do the actual remove. If you really have to manipulate (remove items) the series without a chart attached, you might try to implement a dummy chart and set that to the series.

Factory Method implementation in actionscript

Hey folks, i ve got this issue implementing the Factory method.
Following is the snippet of the the main chart class which calls ChartFactory's method to attain the proper object. I Type Cast chartobject so as to be able to call the Show method;i m apprehensive about that as well.
container = new VBox();
container.percentWidth = 100;
container.percentHeight = 100;
super.media.addChild(container);
chartObject = new ChartBase();
chartObject = ChartFactory.CreateChartObject(chartType);
IChart(chartObject).Show(o);
container.addChild(chartObject);
legend = new Legend();
legend.dataProvider = IChart(chartObject);
container.addChild(legend);
Following is the snippet of ChartFactory's method:
public static function CreateChartObject(subType:String):ChartBase
{
switch(subType)
{
case ChartFactory.AREA_CHART:
return new AreaCharts();
break;
case ChartFactory.COLUMN_CHART:
return new ColumnCharts();
break;
case ChartFactory.PIE_CHART:
return new PieCharts();
break;
default:
throw new ArgumentError(subType + ": Chart type is not recognized.");
}
}
And following is Show method of one of the several Charts type classes: AreaCharts, PieCharts etc. All of which implements IChart Interface.
public function Show(o:ObjectProxy):void
{
var grids:GridLines;
var stroke:SolidColorStroke;
var horizontalAxis:CategoryAxis;
var verticalAxis:LinearAxis;
var horizontalAxisRenderer:AxisRenderer;
var verticalAxisRenderer:AxisRenderer;
grids = new GridLines();
if(WidgetStylesheet.instance.LineChart_ShowGrid)
grids.setStyle("gridDirection", "both");
else
grids.setStyle("gridDirection", "");
stroke = new SolidColorStroke(WidgetStylesheet.instance.LineChart_GridLineColor, WidgetStylesheet.instance.LineChart_GridLineThickness);
grids.setStyle("horizontalStroke", stroke);
grids.setStyle("verticalStroke", stroke);
horizontalAxis = new CategoryAxis();
horizontalAxis.categoryField = o.LargeUrl.Chart.xField;
horizontalAxis.title = o.LargeUrl.Chart.xAxisTitle.toString();
verticalAxis = new LinearAxis();
verticalAxis.title = o.LargeUrl.Chart.yAxisTitle.toString();
horizontalAxisRenderer = new AxisRenderer();
horizontalAxisRenderer.axis = horizontalAxis;
horizontalAxisRenderer.setStyle("tickLength", 0);
horizontalAxisRenderer.setStyle("showLine", false);
horizontalAxisRenderer.setStyle("showLabels", true);
horizontalAxisRenderer.setStyle("fontSize", WidgetStylesheet.instance.ComputeChartAxisFontSize(o.HeadlineFontSize));
verticalAxisRenderer = new AxisRenderer();
verticalAxisRenderer.axis = verticalAxis;
verticalAxisRenderer.setStyle("tickLength", 0);
verticalAxisRenderer.setStyle("showLine", false);
verticalAxisRenderer.setStyle("fontSize", WidgetStylesheet.instance.ComputeChartAxisFontSize(o.HeadlineFontSize));
this.series = this.m_createSeries(o);
this.horizontalAxis = horizontalAxis;
this.horizontalAxisRenderers = [horizontalAxisRenderer];
this.verticalAxis = verticalAxis;
this.verticalAxisRenderers = [verticalAxisRenderer];
this.backgroundElements = [grids];
}
I'm afraid that there is more than one issue with this code. Unfortunately it is not obvious why your chart doesn't show up so you may apply some of advices below and use debugger to analyse the issue.
There is no point in creating ChartBase instance if you are going to change value of chartObject reference in the next line
chartObject = new ChartBase();
chartObject = ChartFactory.CreateChartObject(chartType);
If the API of your charts is IChart your factory should return IChart instead of casting.
public static function CreateChartObject(subType:String):IChart
Make sure that you are returning instances of the correct class from the factory. i.e. that you are returning your subclass of standard PieChart. Generally it's not the best idea to extend the class keeping the same name and just changing the package.
Once again, if you are not sure if the program enters some function use the Flash Builder debugger to check this. I can't imagine development without debugger.
Some thoughts:
you call the Show method, pass it some object but nowhere in that method is any child added to a displayObject. What exactly is Show supposed to do?
a lot of member variables in your classes start with UpperCase. The compiler can easily confuse those with class names, in case your classes are named the same. Bad practice to start variable and function names with capitals.
If your casting an instance to another class or interface fails, you will get a runtime error. Those are easy to debug using the Flash Builder debugger.
Hey ppl..
i found out wat wnt wrng..as olwys it wa "I".
I ve a habit of mkin mock ups secluded from the main project n dn integrate it. So in mock up i hd used an xml whch hd a format slightly diff dn d one being used in the main project.
N i hd a conditional chk to return from the prog if certain value doesnt match, n due to faulty xml i did'nt.
So this more a lexical error than a logical one.
Sorry n Thanx evryone for responding.

Resources