Skip to content

Commit fefaa81

Browse files
committed
switch does not work with complex types
1 parent 1390f1c commit fefaa81

2 files changed

Lines changed: 76 additions & 0 deletions

File tree

‎QUESTIONS.md‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,5 +76,25 @@
7676
persons[2] = new Person()
7777
```
7878

79+
- why does switch not work with complex types ?
80+
when can add a complex type to a hash and its hashCode and equals method is used
81+
why not use equals for switch ?
82+
also how does type-safety work for switch ?
83+
84+
```java
85+
Person p1 = new Person("p1");
86+
Person p2 = new Person("p2");
7987

88+
// does not work
89+
switch (p2) {
90+
case p1:
91+
System.out.println("switch to p1");
92+
break;
93+
case p2:
94+
System.out.println("switch to p1");
95+
break;
96+
default:
97+
System.out.println("nothing to switch");
98+
}
99+
```
80100

‎src/Main.java‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,5 +36,61 @@ public static void main(String[] args) {
3636
// persons[2] = p2;
3737

3838
System.out.println("persons: " + Arrays.toString(persons));
39+
40+
// does not work
41+
// https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
42+
// A switch works with the byte, short, char, and int primitive data types.
43+
// It also works with enumerated types (discussed in Enum Types), the String class,
44+
// and a few special classes that wrap certain primitive types:
45+
// Character, Byte, Short, and Integer (discussed in Numbers and Strings).
46+
// why is this rule ? when adding to map works with the object's hashCode and equals ?
47+
// switch (p2) {
48+
// case p1:
49+
// System.out.println("switch to p1");
50+
// break;
51+
// case p2:
52+
// System.out.println("switch to p1");
53+
// break;
54+
// default:
55+
// System.out.println("nothing to switch");
56+
// }
57+
58+
System.out.println("8'th month is: " + monthName(8));
59+
}
60+
61+
public static String monthName(int month) {
62+
String monthString;
63+
64+
// is type-safe so `case "10"` will throw a type error
65+
switch (month) {
66+
case 1: monthString = "January";
67+
break;
68+
case 2: monthString = "February";
69+
break;
70+
case 3: monthString = "March";
71+
break;
72+
case 4: monthString = "April";
73+
break;
74+
case 5: monthString = "May";
75+
break;
76+
case 6: monthString = "June";
77+
break;
78+
case 7: monthString = "July";
79+
break;
80+
case 8: monthString = "August";
81+
break;
82+
case 9: monthString = "September";
83+
break;
84+
case 10: monthString = "October";
85+
break;
86+
case 11: monthString = "November";
87+
break;
88+
case 12: monthString = "December";
89+
break;
90+
default: monthString = "Invalid month";
91+
break;
92+
}
93+
94+
return monthString;
3995
}
4096
}

0 commit comments

Comments
 (0)