Re: Making a char a CharSequence.
Hakusa@gmail.com wrote:
// CHAR CAN'T CONVERT TO CHARSEQUENCE AS REQUIRED!
char Char = expression.charAt(i); // Get the indexy
String alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String numb = "1234567890";
if ( alpha.contains(Char) || numb.contains(Char) ) {
After several attempts, I think I see what you mean.
There exists a String.contains(CharSequence) method, but no
String.contains(char). How does one go about achieving the equivalent of
the fictional method...?
The direct answer is that you can create a CharSequence with a single
char, using Character.toString(char). Or you could create a compact
implementation if you really had to (performance, memory, whatever)
(code below).
The simpler way is do what we did before 1.5: Use String.indexOf != -1.
BTW: It's less confusing if you stick to code conventions.
Tom Hawtin
public final class SingletonCharSequence implements CharSequence {
private final char c;
public SingletonCharSequence(char c) {
this.c = c;
}
public char charAt(int index) {
if (index != 0) {
throw new IndexOutOfBoundsException();
}
return c;
}
public int length() {
return 1;
}
public CharSequence subSequence(int start, int end) {
if (start == end) {
if (start == 0 || start == 1) {
return "";
} else {
throw new IndexOutOfBoundsException();
}
} else if (start == 0 && end == 1) {
return this;
} else {
throw new IndexOutOfBoundsException();
}
}
@Override
public String toString() {
return Character.toString(c);
}
// Nice to have method (a.k.a. premature generalisation...)
@Override
public int hashCode() {
return c;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof SingletonCharSequence) {
return false;
}
SingletonCharSequence other = (SingletonCharSequence)obj;
return this.c == other.c;
}
}
(Usual disclaimer...)