I'm trying to convert the below if statement into a switch expression.
public static int parseDays(String durationString) {
String[] parts = durationString.split(" ");
if (parts.length == 2) {
return unitValueCalculation(parts[1], parts[0]);
}
else if (parts.length == 1)
{
if (parts[0].equalsIgnoreCase("once")) return 1;
}
return 0;
}
This is what I've got:
public static int parseDays(String durationString) {
switch (durationString) {
case durationString.split(" ").length == 2 -> unitValueCalculation(parts[1], parts[2]);
}
I'm not sure what to do about the case statement, though.
Any ideas would be appreciated.
The code you've provided can be made into a switch-expression like that:
public static int parseDays(String durationString) {
String[] parts = durationString.split(" ");
return switch(parts.length) {
case 2 -> unitValueCalculation(parts[1], parts[0]);
case 1 -> parts[0].equalsIgnoreCase("once") ? 1 : 0;
default -> 0;
};
}
The length of the parts array should be used inside the parentheses () of the switch. And each particular length (1 and 2) should be used as a case-constant.
The default case covers all unspecified array sizes.
Worrying about my web application's performances, I am wondering which of "if/else" or switch statement is better regarding performance?
I totally agree with the opinion that premature optimization is something to avoid.
But it's true that the Java VM has special bytecodes which could be used for switch()'s.
See WM Spec (lookupswitch and tableswitch)
So there could be some performance gains, if the code is part of the performance CPU graph.
That's micro optimization and premature optimization, which are evil. Rather worry about readabililty and maintainability of the code in question. If there are more than two if/else blocks glued together or its size is unpredictable, then you may highly consider a switch statement.
Alternatively, you can also grab Polymorphism. First create some interface:
public interface Action {
void execute(String input);
}
And get hold of all implementations in some Map. You can do this either statically or dynamically:
Map<String, Action> actions = new HashMap<String, Action>();
Finally replace the if/else or switch by something like this (leaving trivial checks like nullpointers aside):
actions.get(name).execute(input);
It might be microslower than if/else or switch, but the code is at least far better maintainable.
As you're talking about webapplications, you can make use of HttpServletRequest#getPathInfo() as action key (eventually write some more code to split the last part of pathinfo away in a loop until an action is found). You can find here similar answers:
Using a custom Servlet oriented framework, too many servlets, is this an issue
Java Front Controller
If you're worrying about Java EE webapplication performance in general, then you may find this article useful as well. There are other areas which gives a much more performance gain than only (micro)optimizing the raw Java code.
It's extremely unlikely that an if/else or a switch is going to be the source of your performance woes. If you're having performance problems, you should do a performance profiling analysis first to determine where the slow spots are. Premature optimization is the root of all evil!
Nevertheless, it's possible to talk about the relative performance of switch vs. if/else with the Java compiler optimizations. First note that in Java, switch statements operate on a very limited domain -- integers. In general, you can view a switch statement as follows:
switch (<condition>) {
case c_0: ...
case c_1: ...
...
case c_n: ...
default: ...
}
where c_0, c_1, ..., and c_N are integral numbers that are targets of the switch statement, and <condition> must resolve to an integer expression.
If this set is "dense" -- that is, (max(ci) + 1 - min(ci)) / n > α, where 0 < k < α < 1, where k is larger than some empirical value, a jump table can be generated, which is highly efficient.
If this set is not very dense, but n >= β, a binary search tree can find the target in O(2 * log(n)) which is still efficient too.
For all other cases, a switch statement is exactly as efficient as the equivalent series of if/else statements. The precise values of α and β depend on a number of factors and are determined by the compiler's code-optimization module.
Finally, of course, if the domain of <condition> is not the integers, a switch
statement is completely useless.
Use switch!
I hate to maintain if-else-blocks! Have a test:
public class SpeedTestSwitch
{
private static void do1(int loop)
{
int temp = 0;
for (; loop > 0; --loop)
{
int r = (int) (Math.random() * 10);
switch (r)
{
case 0:
temp = 9;
break;
case 1:
temp = 8;
break;
case 2:
temp = 7;
break;
case 3:
temp = 6;
break;
case 4:
temp = 5;
break;
case 5:
temp = 4;
break;
case 6:
temp = 3;
break;
case 7:
temp = 2;
break;
case 8:
temp = 1;
break;
case 9:
temp = 0;
break;
}
}
System.out.println("ignore: " + temp);
}
private static void do2(int loop)
{
int temp = 0;
for (; loop > 0; --loop)
{
int r = (int) (Math.random() * 10);
if (r == 0)
temp = 9;
else
if (r == 1)
temp = 8;
else
if (r == 2)
temp = 7;
else
if (r == 3)
temp = 6;
else
if (r == 4)
temp = 5;
else
if (r == 5)
temp = 4;
else
if (r == 6)
temp = 3;
else
if (r == 7)
temp = 2;
else
if (r == 8)
temp = 1;
else
if (r == 9)
temp = 0;
}
System.out.println("ignore: " + temp);
}
public static void main(String[] args)
{
long time;
int loop = 1 * 100 * 1000 * 1000;
System.out.println("warming up...");
do1(loop / 100);
do2(loop / 100);
System.out.println("start");
// run 1
System.out.println("switch:");
time = System.currentTimeMillis();
do1(loop);
System.out.println(" -> time needed: " + (System.currentTimeMillis() - time));
// run 2
System.out.println("if/else:");
time = System.currentTimeMillis();
do2(loop);
System.out.println(" -> time needed: " + (System.currentTimeMillis() - time));
}
}
My C# standard code for benchmarking
I remember reading that there are 2 kinds of Switch statements in Java bytecode. (I think it was in 'Java Performance Tuning' One is a very fast implementation which uses the switch statement's integer values to know the offset of the code to be executed. This would require all integers to be consecutive and in a well-defined range. I'm guessing that using all the values of an Enum would fall in that category too.
I agree with many other posters though... it may be premature to worry about this, unless this is very very hot code.
According to Cliff Click in his 2009 Java One talk A Crash Course in Modern Hardware:
Today, performance is dominated by patterns of memory access. Cache misses dominate – memory is the new disk. [Slide 65]
You can get his full slides here.
Cliff gives an example (finishing on Slide 30) showing that even with the CPU doing register-renaming, branch prediction, and speculative execution, it's only able to start 7 operations in 4 clock cycles before having to block due to two cache misses which take 300 clock cycles to return.
So he says to speed up your program you shouldn't be looking at this sort of minor issue, but on larger ones such as whether you're making unnecessary data format conversions, such as converting "SOAP → XML → DOM → SQL → …" which "passes all the data through the cache".
In my test the better performance is ENUM > MAP > SWITCH > IF/ELSE IF in Windows7.
import java.util.HashMap;
import java.util.Map;
public class StringsInSwitch {
public static void main(String[] args) {
String doSomething = null;
//METHOD_1 : SWITCH
long start = System.currentTimeMillis();
for (int i = 0; i < 99999999; i++) {
String input = "Hello World" + (i & 0xF);
switch (input) {
case "Hello World0":
doSomething = "Hello World0";
break;
case "Hello World1":
doSomething = "Hello World0";
break;
case "Hello World2":
doSomething = "Hello World0";
break;
case "Hello World3":
doSomething = "Hello World0";
break;
case "Hello World4":
doSomething = "Hello World0";
break;
case "Hello World5":
doSomething = "Hello World0";
break;
case "Hello World6":
doSomething = "Hello World0";
break;
case "Hello World7":
doSomething = "Hello World0";
break;
case "Hello World8":
doSomething = "Hello World0";
break;
case "Hello World9":
doSomething = "Hello World0";
break;
case "Hello World10":
doSomething = "Hello World0";
break;
case "Hello World11":
doSomething = "Hello World0";
break;
case "Hello World12":
doSomething = "Hello World0";
break;
case "Hello World13":
doSomething = "Hello World0";
break;
case "Hello World14":
doSomething = "Hello World0";
break;
case "Hello World15":
doSomething = "Hello World0";
break;
}
}
System.out.println("Time taken for String in Switch :"+ (System.currentTimeMillis() - start));
//METHOD_2 : IF/ELSE IF
start = System.currentTimeMillis();
for (int i = 0; i < 99999999; i++) {
String input = "Hello World" + (i & 0xF);
if(input.equals("Hello World0")){
doSomething = "Hello World0";
} else if(input.equals("Hello World1")){
doSomething = "Hello World0";
} else if(input.equals("Hello World2")){
doSomething = "Hello World0";
} else if(input.equals("Hello World3")){
doSomething = "Hello World0";
} else if(input.equals("Hello World4")){
doSomething = "Hello World0";
} else if(input.equals("Hello World5")){
doSomething = "Hello World0";
} else if(input.equals("Hello World6")){
doSomething = "Hello World0";
} else if(input.equals("Hello World7")){
doSomething = "Hello World0";
} else if(input.equals("Hello World8")){
doSomething = "Hello World0";
} else if(input.equals("Hello World9")){
doSomething = "Hello World0";
} else if(input.equals("Hello World10")){
doSomething = "Hello World0";
} else if(input.equals("Hello World11")){
doSomething = "Hello World0";
} else if(input.equals("Hello World12")){
doSomething = "Hello World0";
} else if(input.equals("Hello World13")){
doSomething = "Hello World0";
} else if(input.equals("Hello World14")){
doSomething = "Hello World0";
} else if(input.equals("Hello World15")){
doSomething = "Hello World0";
}
}
System.out.println("Time taken for String in if/else if :"+ (System.currentTimeMillis() - start));
//METHOD_3 : MAP
//Create and build Map
Map<String, ExecutableClass> map = new HashMap<String, ExecutableClass>();
for (int i = 0; i <= 15; i++) {
String input = "Hello World" + (i & 0xF);
map.put(input, new ExecutableClass(){
public void execute(String doSomething){
doSomething = "Hello World0";
}
});
}
//Start test map
start = System.currentTimeMillis();
for (int i = 0; i < 99999999; i++) {
String input = "Hello World" + (i & 0xF);
map.get(input).execute(doSomething);
}
System.out.println("Time taken for String in Map :"+ (System.currentTimeMillis() - start));
//METHOD_4 : ENUM (This doesn't use muliple string with space.)
start = System.currentTimeMillis();
for (int i = 0; i < 99999999; i++) {
String input = "HW" + (i & 0xF);
HelloWorld.valueOf(input).execute(doSomething);
}
System.out.println("Time taken for String in ENUM :"+ (System.currentTimeMillis() - start));
}
}
interface ExecutableClass
{
public void execute(String doSomething);
}
// Enum version
enum HelloWorld {
HW0("Hello World0"), HW1("Hello World1"), HW2("Hello World2"), HW3(
"Hello World3"), HW4("Hello World4"), HW5("Hello World5"), HW6(
"Hello World6"), HW7("Hello World7"), HW8("Hello World8"), HW9(
"Hello World9"), HW10("Hello World10"), HW11("Hello World11"), HW12(
"Hello World12"), HW13("Hello World13"), HW14("Hello World4"), HW15(
"Hello World15");
private String name = null;
private HelloWorld(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void execute(String doSomething){
doSomething = "Hello World0";
}
public static HelloWorld fromString(String input) {
for (HelloWorld hw : HelloWorld.values()) {
if (input.equals(hw.getName())) {
return hw;
}
}
return null;
}
}
//Enum version for betterment on coding format compare to interface ExecutableClass
enum HelloWorld1 {
HW0("Hello World0") {
public void execute(String doSomething){
doSomething = "Hello World0";
}
},
HW1("Hello World1"){
public void execute(String doSomething){
doSomething = "Hello World0";
}
};
private String name = null;
private HelloWorld1(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void execute(String doSomething){
// super call, nothing here
}
}
/*
* http://stackoverflow.com/questions/338206/why-cant-i-switch-on-a-string
* https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-3.html#jvms-3.10
* http://forums.xkcd.com/viewtopic.php?f=11&t=33524
*/
For most switch and most if-then-else blocks, I can't imagine that there are any appreciable or significant performance related concerns.
But here's the thing: if you're using a switch block, its very use suggests that you're switching on a value taken from a set of constants known at compile time. In this case, you really shouldn't be using switch statements at all if you can use an enum with constant-specific methods.
Compared to a switch statement, an enum provides better type safety and code that is easier to maintain. Enums can be designed so that if a constant is added to the set of constants, your code won't compile without providing a constant-specific method for the new value. On the other hand, forgetting to add a new case to a switch block can sometimes only be caught at run time if you're lucky enough to have set your block up to throw an exception.
Performance between switch and an enum constant-specific method should not be significantly different, but the latter is more readable, safer, and easier to maintain.
A good explanation at the link below:
https://www.geeksforgeeks.org/switch-vs-else/
Test(c++17)
1 - If grouped
2 - If sequential
3 - Goto Array
4 - Switch Case - Jump Table
https://onlinegdb.com/Su7HNEBeG
Speed: A switch statement might prove to be faster than ifs provided number of cases are good. If there are only few cases, it might not effect the speed in any case. Prefer switch if the number of cases are more than 5 otherwise, you may use if-else too. If a switch contains more than five items, it’s implemented using a lookup table or a hash list. This means that all items get the same access time, compared to a list of if:s where the last item takes much more time to reach as it has to evaluate every previous condition first.
Clarity in readability: A switch looks much cleaner when you have to combine cases. Ifs are quite vulnerable to errors too. Missing an else statement can land you up in havoc. Adding/removing labels is also easier with a switch and makes your code significantly easier to change and maintain.
Example:->
String environment="QA";
switch(environment.toLowerCase().trim()) {
case "qa":
System.out.println(environment+" :"+"Environment running the TestCases");
break;
case "Stage":
System.out.println(environment+" :"+"Environment running the TestCases");
break;
case "Dev":
System.out.println(environment+" :"+"Environment running the TestCases");
break;
case "UAT":
System.out.println(environment+" :"+"Environment running the TestCases");
break;
case "Prod":
System.out.println(environment+" :"+"Environment running the TestCases");
break;
default:
System.out.println(environment+" :"+"Please pass the right Environment");
break;
}
String browser="Chrome";
if (browser.equals("chrome")) {
System.out.println(browser + ": " + " Launch the Browser");
} else if (browser.equals("safari")) {
System.out.println(browser + ": " + " Launch the Browser");
} else if (browser.equals("IE")) {
System.out.println(browser + ": " + " Launch the Browser");
} else if (browser.equals("opera")) {
System.out.println(browser + ": " + " Launch the Browser");
} else if (browser.equals("Edge")) {
System.out.println(browser + ": " + " Launch the Browser");
} else {
System.out.println("Please pass the right browser");
}
When I start my tests I want to see an Exception, but programm just stay on the one line "mobileTelephony.driver" and don't throught exception. I don't understand why?
#Test(groups = {"non-basic"})
#Parameters({"idCategory"})
public void checkSearchForm(int idCategory) throws InterruptedException {
String categoryName;
int location = 1;
StackOfCategories sub1Stack = TestSuiteMobileTelephony.sub1Stack;
boolean isItSubCategory;
basePage.getBasePage();
basePage.clickCategoryName(idCategory);
MobileTelephonyPage mobileTelephony = PageFactory.initElements(basePage.driver, MobileTelephonyPage.class);
while (location <= 3) {
mobileTelephony.clickChangeLocation(location);
for(int i = 1; i <= sub1Stack.size(); i++) {
if (location == 1) {
categoryName = sub1Stack.getCategory(i).getNameEn();
} else if (location == 2) {
categoryName = sub1Stack.getCategory(i).getNameRu();
} else {
categoryName = sub1Stack.getCategory(i).getNameUk();
}
mobileTelephony.writeInSearchFormAndClick(categoryName);
try {
mobileTelephony.driver.findElement(By.xpath(".//div[#id='breadcrumbs']/span1"));
} catch(Exception e){
e.printStackTrace();
mobileTelephony.back();
}
isItSubCategory = true;
AssertMessage.assertTrueNavigateSubCategory(categoryName, isItSubCategory);
mobileTelephony.back();
}
location++;
}
}
Mobail Telefony code
public class MobileTelephonyPage extends BasePage {
public void clickAndWriteNumber(String number) throws AWTException {
String[] numsArray = number.split("");
number1.clear();
number1.click();
Robot robot = new Robot();
// Constryction
for(int i = 0; i < numsArray.length; i++) {
switch(Integer.parseInt(numsArray[i])) {
case 0 :
robot.keyPress(KeyEvent.VK_0);
break;
case 1 :
robot.keyPress(KeyEvent.VK_1);
break;
case 2 :
robot.keyPress(KeyEvent.VK_2);
break;
case 3 :
robot.keyPress(KeyEvent.VK_3);
break;
case 4 :
robot.keyPress(KeyEvent.VK_4);
break;
case 5 :
robot.keyPress(KeyEvent.VK_5);
break;
case 6 :
robot.keyPress(KeyEvent.VK_6);
break;
case 7 :
robot.keyPress(KeyEvent.VK_7);
break;
case 8 :
robot.keyPress(KeyEvent.VK_8);
break;
case 9 :
robot.keyPress(KeyEvent.VK_9);
break;
}
}
}
public MobileTelephonyPage(WebDriver driver) {
super(driver);
}
public int getHeightImg(int number) {
int height = driver.findElement(By.xpath("(.//div[#class='icon']/img)[" + number + "]")).getSize().getHeight();
return height;
}
public int getWidthImg(int number) {
int width = driver.findElement(By.xpath("(.//div[#class='icon']/img)[" + number + "]")).getSize().getWidth();
return width;
}
public MobileTelephonyPage back() {
driver.navigate().back();
return this;
}
public String getCurrentURL() {
return driver.getCurrentUrl();
}
public void clickOperator(String linkText) {
driver.findElement(By.linkText(linkText)).click();
}
}
in debug program stop in the next snipet of code(class HttpCommandExecutor)
this.log("profiler", new HttpProfilerLogEntry(command.getName(), true));
HttpResponse e = this.client.execute(httpRequest, true);
this.log("profiler", new HttpProfilerLogEntry(command.getName(), false));
No Exception is thrown.
Probably the code needs a long time to be executed or it is in a livelock.
A livelock is a situation when a function is executed but never ends. For example because in a for loop you loose to update a variable so the test is always true
Edited after new informations
From the javadoc of WebDriver:
This method is affected by the 'implicit wait' times in force at the
time of execution. The findElement(..) invocation will return a
matching row, or try again repeatedly until the configured timeout is
reached. findElement should not be used to look for non-present
elements, use findElements(By) and assert zero length response
instead.
As you can see the the function could not returns exactly as mentioned on the first two lines of my post.
This program reads from a file and types its contents out line by line or at the ends of sentences depending on config settings. It uses Java.awt.Robot to do this, and all the keyboard characters can be typed except the apostrophe and quotation characters. The key is function on my keyboard and other scripts can type it. I can't figure out why this program cannot type it correctly.
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
public class SmartRobot extends Robot {
public int count70=0;
public SmartRobot() throws AWTException {
super();
}
public void keyType(int keyCode) {
if(keyCode == -1)
return;
keyPress(keyCode);
delay(2);
keyRelease(keyCode);
}
public void keyType(int keyCode, int keyCodeModifier) {
keyPress(keyCodeModifier);
keyPress(keyCode);
delay(2);
keyRelease(keyCode);
keyRelease(keyCodeModifier);
}
public void type(String text) {
if(text.length()>1 && text.substring(0, 1).equals("\\")){
Driver.codeTimeEnd = System.nanoTime();
delay(Integer.parseInt(text.substring(2, text.length()))-(int) (Driver.codeTimeEnd-Driver.codeTimeStart)/1000000000);
return;
}
String textUpper = text.toUpperCase();
for (int i=0; i<text.length(); ++i) {
typeChar(textUpper.charAt(i));
}
if(!Driver.enterAtPeriods || !Driver.enterUnder60)keyPress(KeyEvent.VK_ENTER);
Driver.codeTimeEnd = System.nanoTime();
if(!Driver.enterUnder60)
delay(Driver.lineDelay-(int)(Driver.codeTimeEnd- Driver.codeTimeStart)/1000000000);
else
delay(2);
}
public void typeChar(char c) {
boolean shift = true;
int keyCode;
switch (c) {
case '~':keyCode = (int)'`';break;
case '!':keyCode = (int)'1';break;
case '#':keyCode = (int)'2';break;
case '#':keyCode = (int)'3';break;
case '$':keyCode = (int)'4';break;
case '%':keyCode = (int)'5';break;
case '^':keyCode = (int)'6';break;
case '&':keyCode = (int)'7';break;
case '*':keyCode = (int)'8';break;
case '(':keyCode = (int)'9';break;
case ')':keyCode = (int)'0';break;
case ':':keyCode = (int)';';break;
case '_':keyCode = (int)'-';break;
case '+':keyCode = (int)'=';break;
case '|':keyCode = (int)'\\';break;
case '"':keyCode = (int)'\'';break;
case '?':keyCode = (int)'/';break;
case '{':keyCode = (int)'[';break;
case '}':keyCode = (int)']'; break;
case '<':keyCode = (int)',';break;
case '>':keyCode = (int)'.';break;
case '“':keyCode = (int)'\'';break;
case '”':keyCode = (int)'\'';break;
case '…':keyCode = (int)' ';break;
case '‘':keyCode = (int)'\'';break;
case '’':keyCode = (int)'\'';break;
default:
// System.out.println(c);
keyCode = (int)c;
// System.out.println(keyCode);
shift = false;
}
if(Driver.enterUnder60){
count70++;
if(count70>70)
if(c == ' '){
count70 = 0;
keyType(KeyEvent.VK_ENTER);
delay(Driver.lineDelay-(int)(Driver.codeTimeEnd-Driver.codeTimeStart)/1000000000);
return;
}
}
if(Driver.enterAtPeriods){
if(c == '.'){
count70 = 0;
keyType(KeyEvent.VK_ENTER);
delay(Driver.lineDelay-(int)(Driver.codeTimeEnd-Driver.codeTimeStart)/1000000000);
return;
}
}
if (shift){
keyType(keyCode, KeyEvent.VK_SHIFT);
System.out.println("works");
}
else
keyType(keyCode);
}
private int charToKeyCode(char c) {
switch (c) {
case ':':
return ';';
}
return (int)c;
}
}
The infile can be whatever you want it to be, and all characters will be shown, but the " will not be typed. I don't know if the type() method is ever accessed in its case.
Here is an example input:
"Hi, my name is koikoi."
The output comes out like this:
Hi, my name is koikoi.
When it should have the quotations on it. The typer does not recognize/read them. I can't find any flaws in my code and would like some advice. I can add the main method if requested.
I have been scouring the internet for answers to my problem. I have found some good advice and have changed my original code, but I am yet to discover the answer to my initial problem.
I am trying to take string data from a series of Jtextfields and writing them to an arraylist, and then in turn taking the written data from the arraylist and transfering it to the same text fields.
public class Form extends javax.swing.JFrame {
public ArrayList<Personal> personalList;
public ArrayList<Business> businessList;
public ArrayList<Personal> displayPersonalList;
public ArrayList<Business> displayBusinessList;
public Form() {
initArrayLists();
}
private void initArrayLists(){
personalList = new ArrayList<Personal>();
businessList = new ArrayList<Business>();
displayPersonalList = new ArrayList<Personal>();
displayBusinessList = new ArrayList<Business>();
}
this is my submit button that writes to the arraylists.
private void submitButtonActionPerformed(java.awt.event.ActionEvent evt)
{
if (contactTypeLabel.getText().equals("Personal Contact")){
Personal p = new Personal();
p.first = firstNameTF.getText();
p.last = lastNameTF.getText();
p.address = addressTF.getText();
p.s = stateTF.getText();
p.zip = zipTF.getText();
p.phone = phoneTF.getText();
p.email = emailTF.getText();
personalList.add(p);
Personal d = new Personal();
d.first = firstNameTF.getText();
displayPersonalList.add(p);
resetTextFields();
}else if (contactTypeLabel.getText().equals("Business Contact")){
Business b = new Business();
b.first = firstNameTF.getText();
b.last = lastNameTF.getText();
b.address = addressTF.getText();
b.s = stateTF.getText();
b.zip = zipTF.getText();
b.phone = phoneTF.getText();
b.email = emailTF.getText();
businessList.add(b);
Business d = new Business();
d.first = firstNameTF.getText();
displayBusinessList.add(d);
resetTextFields();
}
}
here is the code to change to display mode, with a combobox that should populate for accessing the arraylist to fill the textfields with selected data
private void displayPersonalButtonActionPerformed(java.awt.event.ActionEvent evt)
{
personalFieldViewer();
submitButton.setVisible(false);
displayComboBox.setVisible(true);
clearTextFields();
for (Object item : displayPersonalList) {
displayComboBox.addItem(item);
}
}
this is the code for the combobox action and code to fill the text fields
private void displayComboBoxActionPerformed(java.awt.event.ActionEvent evt)
{
int x;
switch (displayComboBox.getSelectedIndex()){
case 0:
for (x = 0; x < x + 8; x ++) {
switch (x){
case 0 :firstNameTF.setText(personalList.get(x).toString());
break;
case 1 :lastNameTF.setText(personalList.get(x).toString());
break;
case 2 :addressTF.setText(personalList.get(x).toString());
break;
case 3 :stateTF.setText(personalList.get(x).toString());
break;
case 4 :zipTF.setText(personalList.get(x).toString());
break;
case 5 :phoneTF.setText(personalList.get(x).toString());
break;
case 6 :dobTF.setText(personalList.get(x).toString());
break;
case 7 :emailTF.setText(personalList.get(x).toString());
break;
}
}
break;
case 1:
for (x = 8; x < x + 8; x ++) {
switch (x){
case 8 :firstNameTF.setText(personalList.get(x).toString());
break;
case 9 :lastNameTF.setText(personalList.get(x).toString());
break;
case 10 :addressTF.setText(personalList.get(x).toString());
break;
case 11 :stateTF.setText(personalList.get(x).toString());
break;
case 12 :zipTF.setText(personalList.get(x).toString());
break;
case 13 :phoneTF.setText(personalList.get(x).toString());
break;
case 14 :dobTF.setText(personalList.get(x).toString());
break;
case 15 :emailTF.setText(personalList.get(x).toString());
break;
}
}
break;
case 2:
for (x = 16; x < x + 8; x ++) {
switch (x){
case 16 :firstNameTF.setText(personalList.get(x).toString());
break;
case 17 :lastNameTF.setText(personalList.get(x).toString());
break;
case 18 :addressTF.setText(personalList.get(x).toString());
break;
case 19 :stateTF.setText(personalList.get(x).toString());
break;
case 20 :zipTF.setText(personalList.get(x).toString());
break;
case 21 :phoneTF.setText(personalList.get(x).toString());
break;
case 22 :dobTF.setText(personalList.get(x).toString());
break;
case 23 :emailTF.setText(personalList.get(x).toString());
break;
}
}
break;
}
}
here are the classes that hold the variables for the arraylists.
public class Contacts {
public String first, last, address, s, zip, phone, email;
}
public class Personal extends Contacts{
public String dob;
}
public class Business extends Contacts{
public String title, organization;
}
when I alternately try to fill the arraylists with *.add(textfield.getText()); Java will not allow this as well as using variables first=firstNameTF.getText(); then *.add(first); I get the same error message...
Please try to refrain from being negative, and I have read the API regarding arraylists. Thank you.
Your arraylist declarations has type either Personal or Business. So these list cant add a string value. So when you say personalList.add(textfield.getText()); its actually trying to add String object to a list that can contain only Personal object.
Secondly the for loop inside displayComboBoxActionPerformed() method results in an infinite loop. for (x = 0; x < x + 8; x ++). Insted of having different for loops and switch statements you could do something like
private void displayComboBoxActionPerformed(java.awt.event.ActionEvent evt) {
if(displayComboBox.getSelectedIndex() > -1){
int start = displayComboBox.getSelectedIndex() * 8;
for (int x = start; x < start + 8; x ++) {
firstNameTF.setText(personalList.get(x).toString());
}
}
}