Java等效的IEnumerable <char> </char>

时间:2012-09-10 11:47:20

标签: c# java translation

这是我必须转换的C#代码:

static readonly IEnumerable<char> BigAlphas = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();

到目前为止,我已经尝试了以下内容:

static final Iterable<Character> BigAlphas = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();

这给了我错误:

  

不兼容的类型

     

必需:java.lang.Iterable

     

发现:char []

我知道我收到此错误是因为我正在尝试将Iterable<Character>设置为char array,但我不确定还能做些什么来翻译它。

3 个答案:

答案 0 :(得分:2)

简单的String会起作用吗?

 static final String BigAlphas = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

String实现CharSequence,它似乎是你需要的,它还有大量的方法来检查成员资格等。

答案 1 :(得分:1)

static final Iterable<Character> alphabet() {
  return new Iterable<Character>() {

    public final Iterator<Character> iterator() {
      return new Iterator<Character>() {

        private char cursor = 'A';

        public boolean hasNext() {
          return cursor <= 'Z';
        }

        public Character next() {
          return cursor++;
        }

        public void remove() {
          throw new UnsupportedOperationException("cannot remove from stream");
        }
      };
    }
  };
}

用法:

for (final char ch : alphabet()) {
  /* ch in interval [A,Z] */
}

这是一种更通用的形式。

static final Iterable<Character> iterable(final CharSequence seq) {
  return new Iterable<Character>() {

    public final Iterator<Character> iterator() {
      return new Iterator<Character>() {

        private int cursor;

        public boolean hasNext() {
          return cursor < seq.length();
        }

        public Character next() {
          return seq.charAt(cursor++);
        }

        public void remove() {
          throw new UnsupportedOperationException("cannot remove from stream");
        }
      };
    }
  };
}
/* ... */
for (final char ch : iterable("qwertyuiop")) {
  /* ... */
}

答案 2 :(得分:0)

好吧,按照自己的方式行事......如果你不介意使用Guava

Iterable<Character> BigAlphas = Chars.asList("ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray());