Inserting object with different values in a ArrayList - java

I have a JFrame where I insert some informations, these informations I send to a object called "macro". When I hit a JButton "macro" is insert in a ArrayList, called "listaJFP". When I enter with the first informations like, name "Murilo", id "1", and hit the button, my ArrayList receives the correct information, but when I try to insert another name like "Joao", id "2", my ArrayList receives in the first index [0] Joao, 2, and second index[1] Joao, 2. Instead of [0]Murilo,1 and [1]Joao,2. I looked for this problem and I saw someone talking about the reference of the object, in other words, when I change the values of my object "macro" at the same time the values of my ArrayList are changed. Can someone help me, please ? Thanks for the attention !
This is in my class JFramePrincipal:
Macro macro = new Macro();
private List<Macro> listaJFP = new ArrayList<Macro>();
This is in my JButton actionPerformed:
listaJFP.add(macro);
JFrameTabela jfT = new JFrameTabela(listaJFP);
I will try to put more code:
public class JFramePrincipal extends javax.swing.JFrame {
private List<Macro> listaJFP = new ArrayList<Macro>();
Macro macro = new Macro();
String[] arrayNodeName;
String[] listaVelocidade = new String[]{"1024", "1984"};
String[] listaSlot = new String[]{"2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13"};
String[] listaModule86x0 = new String[]{"0", "1"};
String[] listaModule8609 = new String[]{"3", "4"};
String[] listaPort = new String[]{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23"};
String[] listaPortFeGe = new String[]{"0", "1", "2", "3", "4", "5", "6", "7"};
String[] nodeType = new String[]{"8609", "8630", "8660"};
private void jButtonGerarMacroActionPerformed(java.awt.event.ActionEvent evt) {
try {
if (jCheckBoxFSP.isSelected() == true) {
macro.setVpnName(jFormattedTextFieldFSP.getValue().toString());
} else if (jCheckBoxSP.isSelected() == true) {
macro.setVpnName(jFormattedTextFieldSP.getValue().toString());
}
macro.velocidade = jComboBoxVelocidade.getSelectedItem().toString();
if (jTextVLAN.isEnabled() == true) {
int vlanInt;
boolean ok = false;
vlanInt = Integer.parseInt(jTextVLAN.getText());
do {
if (vlanInt >= 1 && vlanInt <= 4094) {
macro.vlan = jTextVLAN.getText();
gerar();
jButtonExecutarMacro.setEnabled(true);
} else {
JOptionPane.showMessageDialog(null, "VLAN deve ser maior do que 0 e menor do que 4094", "Mensagem", JOptionPane.ERROR_MESSAGE);
jTextVLAN.grabFocus();
jButtonExecutarMacro.setEnabled(false);
}
} while (ok);
} else {
macro.vlan = null;
gerar();
jButtonExecutarMacro.setEnabled(true);
jButtonGerarMacro.setEnabled(false);
}
private void jButtonExibirResultadoActionPerformed(java.awt.event.ActionEvent evt) {
if(jCheckBoxE1.isSelected() == true){
listaJFP.add(macro);
Macro macro = new Macro();
JFrameTabela jfT = new JFrameTabela(listaJFP);
}

Did you make sure to create a new Macro for every input from GUI
You have to Create a new Macro like this
public void actionPerformed(ActionEvent e){
Macro macro = new Macro();
listaJFP.add(macro);
}
// so it create a totally new Macro object everytime
Edit: After OP edit with more code
You need to create to new Macro inside to the first ActionPerformed because that's where you're manipulating the data. And why do you have two different actionperformed for a similar task?

Related

Given a set of sets, how to efficiently find sets that have at least 1 member in common?

Let's say we're given a set of sets, for example:
Set<String> s1 = Set.of("1", "2", "3", "4", "5", "7");
Set<String> s2 = Set.of("10", "20", "30", "40", "50");
Set<String> s3 = Set.of("100", "200", "300", "400", "500", "7", "9");
Set<String> s4 = Set.of("1000", "2000", "3000", "4000", "5000");
Set<String> s5 = Set.of("100000", "200000", "300000", "400000", "500000", "9");
How to find the collection of sets where there is member intersection? In this example, s1 and s3 have overlap as do s3 and s5.
The inefficient solution would be to
List<Set<String>> sets = List.of(s1, s2, s3, s4, s5);
for (Set<String> tester : sets) {
sets.remove(tester);
for (String s: tester) {
for (Set<String> target : sets) {
if (target.contains(s)) {
// record match
}
}
}
Can a better time complexity be acheived?

IN query with DynamoDB table is not working

ScanRequest with IN on a list field is not matching with the entries in DynamoDB.
Code:
Map<String, AttributeValue> userAttributeValues = new HashMap<>();
userAttributeValues.put(":topic1", new AttributeValue().withS("5"));
userAttributeValues.put(":topic2", new AttributeValue().withS("11"));
ScanRequest scanRequest = new ScanRequest()
.withTableName("user")
.withFilterExpression("subscribedTopics IN (:topic1, :topic2)")
.withProjectionExpression("userId")
.withExpressionAttributeValues(userAttributeValues);
ScanResult result = dynamoDBClient.scan(scanRequest);
System.out.println("Number of results: " + result.getCount());
for (Map<String, AttributeValue> userItemsMap : result.getItems()) {
AttributeValue userIdAttributeValue = userItemsMap.get("userId");
String userId = userIdAttributeValue.getS();
}
User item with valid entry
{ "subscribedTopics": [ "2", "5", "8", "1", "3", "4", "6", "7", "11" ], "userId": "Andrew.Green" }
Used combination of CONTAINS and OR and it worked.
ScanRequest scanRequest = new ScanRequest()
.withTableName("user")
.withFilterExpression("contains(subscribedTopics, :topic1) or contains(subscribedTopics, :topic2)")
.withProjectionExpression("userId")
.withExpressionAttributeValues(userAttributeValues);enter code here

Send Byte from jComboBox

I have a jComboBox with these values:
String[] preset = { "1", "2", "3", "4", "5" };
So if "1" is selected then i want to add a byte to my OutputStream.
byte preset1 = 0X01;
based on the selection in the combobox. I thought it might be this but it gives a NullPointerException.
byte preset = (byte)setPresetcomboBox.getSelectedItem();
try {
byte[] command = {(byte) startTx, address, setPreset, 0x00, preset, endTx, 0x0F};
TwoWaySerialComm.SerialWriter sw = new TwoWaySerialComm.SerialWriter(
twoWaySerCom.serialPort.getOutputStream());
sw.out.write(command);
} catch (IOException e) {
e.printStackTrace();
}
What am i doing wrong here? Apologies if this is obvious, this is my first ever project.
This was solved by changing
String[] preset = { "1", "2", "3", "4", "5" };
to
Byte[] preset = { 1, 2, 3, 4, 5};
making the combobox like this:
setPresetcomboBox = new JComboBox<Byte>(preset);
and my action performed:
byte _preset = (Byte)setPresetcomboBox.getSelectedItem();

How to Extract JSON value outside of Array

At the moment I can loop through my JSON array ''pos" and store all the variables within that into a array list.
What I'm trying to do:
How can I easily parse tour & date which are outside the "pos" array?
I would like to store the values in "tour" & "date" into two separate string variables.
My understanding: json.getJSONArray() can't be used in this case, as json.getJSONArray(TAG_MESSAGES); only pulls in "pos" array data.
JSON Structure:
{
"pos": [
{
"pos": "",
"person": "",
"thur": "",
"score": "",
"round": ""
},
{
"pos": "2",
"person": "John",
"thur": "",
"score": "16",
"round": "3"
},
{
"pos": "3",
"person": "Peter Lynch",
"thur": "",
"score": "5",
"round": "2"
}
],
"tour": "Camping",
"date": "Thursday Jul 23 - Sunday Jul 26, 2015"
}
Code to Parse JSON pos array:
// ALL JSON nodes
private static final String TAG_MESSAGES = "pos";
private static final String TAG_ID = "pos";
private static final String TAG_FROM = "person";
private static final String TAG_EMAIL = "thur";
private static final String TAG_SUBJECT = "round";
private static final String TAG_DATE = "score";
// These are outside of array pos
private static final String TAG_TOUR = "tour";
private static final String TAG_TOURDATE = "date";
try {
inbox = json.getJSONArray(TAG_MESSAGES);
inbox.toString();
// looping through All messages
for (int i = 0; i < inbox.length(); i++) {
JSONObject c = inbox.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_FROM, from);
map.put(TAG_EMAIL, mailer);
map.put(TAG_DATE, date);
map.put(TAG_SUBJECT, subject);
// adding HashList to ArrayList
inboxList.add(map);
as you can get a JSONArray from your json , you can get String from it too.
something like this :
json.getString("tour");
json.getString("date");
Try this,
String tour = "", date = "";
try {
if(json.has("tour"))
tour= json.getString("tour");
if(json.has("date"))
date= json.getString("date");
} Catch(Exception e) {
}
Which will not crash even if there is no date/ tour key(if missing)
inbox = json.getJSONArray(TAG_MESSAGES);
String tour=json.getString("tour");
String date=json.getString("date");

How to manipulate an array similar to an ORDER BY clause in SQL?

My data has been placed into an array, but unfortunately not in the order I want it in...
String[][] databaseToArray = {
//{"Name", "Channel", "Description", "Amount", "isReady"},
{"John", "Nick", "likes", "2", "yes" },
{"Drew", "MTV", "dislikes", "4", "no" },
{"Fred", "CNN", "okay", "3", "no" },
{"Beth", "Fox", "valid", "1", "yes" }
};
How do I manipulate this array so that when I loop through it the order is by the amount , similar to SELECT * FROM "databaseToArray" ORDER BY "Amount" aka
String[][] reorganizedArray = {
//{"Name", "Channel", "Description", "Amount", "isReady"},
{"Beth", "Fox", "valid", "1", "yes" },
{"John", "Nick", "likes", "2", "yes" },
{"Fred", "CNN", "okay", "3", "no" },
{"Drew", "MTV", "dislikes", "4", "no" }
};
You'll want to pass a Comparator to the Arrays.sort method. I haven't done Java in 5 years, but it should be easily doable. Maybe someone can clean up this example I'm about to write, since I'm pretty certain I'll get something wrong.
String[][] databaseToArray = {
//{"Name", "Channel", "Description", "Amount", "isReady"},
{"John", "Nick", "likes", "2", "yes" },
{"Drew", "MTV", "dislikes", "4", "no" },
{"Fred", "CNN", "okay", "3", "no" },
{"Beth", "Fox", "valid", "1", "yes" }
};
Arrays.sort(databaseToArray, new Comparator<String[]>() {
public int compare(String[] a, String[] b) {
return a[3].compareTo(b[3]);
}
});
I found the sort method on the processing website, but this is only for One-Dimensional Arrays...
http://processing.org/reference/sort_.html
float[] a = { 3, 5, 2, 4, 1 };
a = sort(a);
println(a);
// Prints 1, 2, 3, 4, 5

Categories