Reputation: 865
New to Java, but I've done some .Net programming. I'm wondering if Java has the equivalent of a .Net eum? Below is an example. I know Java has enum, but you can't assign values to it.
In .Net I could do an enum with values. When used in code I don't have to comment or, when writing new procedures, remember what 0, 1, 2, and 3 represent. I could also use the enum as parameter type in a constructor and then pass AccessType.Full, for instance, in as an argument.
How can I duplicate this is Android Studio?
Public Class Delete
Private Enum AccessType
Full = 0
ReadOnly = 1
Delete = 2
Add = 3
End Enum
Private Sub DeleteIem(sItem As String)
If User.Access = AccessType.Delete Or User.Access = AccessType.Full Then
'delete something here
Else
MsgBox("You do not have access to delete these items.", vbInformation
End If
End Sub
End Class
In Android Studio I have the if{} block below.
if (AllLists.get(pos).Access == 0) {
MsgText += getResources().getString(R.string.info_cat_shared_no) + "\n";
}
else if (AllLists.get(pos).Access == 1){
MsgText += getResources().getString(R.string.info_cat_shared_edit) + "\n";
}
else if (AllLists.get(pos).Access == 2){
MsgText += getResources().getString(R.string.info_cat_shared_no_edit) + "\n";
}
It would turn the code in to below and I wouldn't have to always be checking what 0, 1 ,2, & 3 represent. I looked up Java enums and they are just a list of string, which doesn't work for this, or at least not that I can think to implement it.
if (AllLists.get(pos).Access == AccessType.Full) {
MsgText += getResources().getString(R.string.info_cat_shared_no) + "\n";
}
else if (AllLists.get(pos).Access == AccessType.ReadOnly){
MsgText += getResources().getString(R.string.info_cat_shared_edit) + "\n";
}
else if (AllLists.get(pos).Access == AccessType.Delete){
MsgText += getResources().getString(R.string.info_cat_shared_no_edit) + "\n";
}
Upvotes: 1
Views: 5081
Reputation: 3775
Actually, java enums are a pretty handy object. You can add properties, even methods, if you want. To assign properties, just add the value as an argument to the contructor as in:
public enum AccessType {
Full(0),
ReadOnly(1),
Delete(2),
Add(3);
private final int code;
AccessType(int code) {
this.code = code
}
public int getCode() {
return this.code;
}
}
Upvotes: 4
Reputation: 363
Please have a look at this page from Oracle: http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html
You would have something like this for your ENUM (code untested):
public enum AccessType
{
Full(0),
ReadOnly(1),
Delete(2),
Add(3);
AccessType(int type)
{
this.type = type;
}
}
But the constructor by itself may not be necessary since you can use a switch case like this:
switch(AllLists.get(pos).Access)
{
case Full:
// ...
break;
case ReadOnly:
// ...
break;
case Delete:
// ...
break;
case Add:
// ...
break;
}
Upvotes: 1