enumキーワードで作る特殊なクラスです。
enumはenumerate(イニュームレイトあるいはイヌームレイト)の略で、列挙するの意味です。
一連の値を定義する文法でC言語の列挙型に似ているが、C言語と違って実態は
JDK1.5で導入された、Enumというクラスを継承している。
また、列挙子自体は、static finalな定数(不変オブジェクト)として定義されている。
!= や == は使えますが、Cと違って、< > などの比較演算はできない。
また、この変数に対して、++もできない。
比較をする場合は、列挙子.compareTo(列挙子) で比較する。
intへのキャストもできない。順位番号は、ordinal()メソッドを利用する。
なお、toString()がオーバーライドされているので、表示することが可能
以下では『SortMethod』のクラスを作っています。
この変数に記憶できるのは、{ }の中で列挙したデータを
SortMethod.マージ, SortMethod.バブル, SortMethod.クイックのSortMethodを指定したいずれかだけになります。
なお、
switch文で使用する場合、case文の定数にenum型名の修飾子は省略できます。
各クラスの詳細は次のリンクで調べましょう。
package test;
import java.util.*;//Randomなどのパッケージ用
import java.awt.*;//BorderLayoutなどのパッケージ用
import java.awt.event.*;//MouseListenerなどのパッケージ用
import javax.swing.*;//JPanelなどのパッケージ用
enum SortMethod { マージ, バブル, クイック, };//コンボボックス項目用の列挙型
public class SortTestMulti extends JApplet
{//アプレット時
MainPanel panel;
public void init()
{//ダウンロード直後で実行(コンストラクタの後)
this.getContentPane().add(panel = new MainPanel());
}
public static void main(String[] args)//----------------メイン---------
{//ローカル起動時
TestFrame f = new TestFrame();
}
public void newTestFrame()
{
new TestFrame();
}
}
//--------------------------------------------------------------------------
class TestFrame extends JFrame
{
MainPanel panel = new MainPanel();
public TestFrame()
{//コンストラクタ
this.setTitle("並び替え");
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.getContentPane().add(panel, BorderLayout.CENTER);
this.setSize(600, 480);
this.setVisible(true);
}
}
//--------------------------------------------------------------------------
class MainPanel extends JPanel implements ActionListener
{
SortMethod sortMethod = SortMethod.values()[0];//初期ソート方法
JButton btnRandom = new JButton("乱数生成");
JComboBox comboBox = new JComboBox();
JButton btnSort = new JButton("ソート開始");
static JEditorPane editorPane = new JEditorPane();
int[] a = { 2, 4, 1, 3, 2, 7, 8 };//中間テストでの並び
Random rnd = new Random(54321);
int [] array = a;
public MainPanel()
{
this.setLayout(new BorderLayout());
JPanel panel = new JPanel();
panel.add(btnRandom);//乱数生成ボタン配置
panel.add(comboBox);//乱数生成ボタン配置
panel.add(btnSort);//ソートボタン配置
this.add(panel, BorderLayout.NORTH);
this.editorPane.setFont(new Font("monospaced", Font.PLAIN, 14)); //フォント設定
this.editorPane.setBackground(new Color(255, 255, 255));
this.editorPane.setForeground(new Color(0,0,0));
this.add(new JScrollPane(editorPane), BorderLayout.CENTER);
for( SortMethod en : SortMethod.values() ){//全ての列挙で項目を生成
this.comboBox.addItem(en);
}
this.btnRandom.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String rtnVal = javax.swing.JOptionPane.showInputDialog(MainPanel.this,
"生成個数を入力ください","10"
);
if (rtnVal == null) return;
java.util.regex.Pattern pattern;
pattern = java.util.regex.Pattern.compile("[1-9]?[0-9]*");
java.util.regex.Matcher matcher = pattern.matcher(rtnVal);//上記正規表現とマッチするか?
if(matcher.matches()){
int n = Integer.parseInt(rtnVal);
setRandom(n);// n個の乱数生成
editorPane.setText("");
printArray(MainPanel.this.array);//全てを1行列挙
}
else
{
JOptionPane.showMessageDialog(MainPanel.this,"数字を入力ください",
"エラー", JOptionPane.ERROR_MESSAGE);
}
}
});
this.comboBox.addItemListener( new ItemListener(){
//ユーザにる項目の選択・解除で実行する
public void itemStateChanged(ItemEvent e)
{
JComboBox cBox = (JComboBox)e.getSource(); //イベント発生オブジェクト取得
int idx = cBox.getSelectedIndex();//指定された項目の添え字
MainPanel.this.sortMethod = (SortMethod)cBox.getItemAt(idx);
//System.out.println(MainPanel.this.sortMethod);
}
});
MainPanel.printArray(this.array);//全てを1行列挙
this.btnSort.addActionListener(this);
}
void setRandom(int n){//--------乱数を n個生成
array = new int[n];
for (int i = 0; i < n; i++){
array[i] = rnd.nextInt(1000);
}
}
static void printArray(int[] array, int left, int right, int width)
{// ----配列 array の指定範囲を、列挙 なお、1要素は右よせ幅指定で行う
for (int i = left; i <= right; i++)
{
String s = String.format("%" + width + "d" , array[i]);
editorPane.replaceSelection(s);
}
}
static void lastSelect(){//末尾を選択
javax.swing.text.Document document = editorPane.getDocument();
int len = document.getLength();
editorPane.setSelectionStart(len);//末尾を選択
}
static void printArray(int[] array)
{// -----デフォルト幅指定で、全てのarray配列を、末尾に列挙後に改行する。
lastSelect();//末尾を選択
printArray( array, 0, array.length- 1 , 5);
editorPane.replaceSelection("\n");
}
public void actionPerformed(ActionEvent e)//-------------ソート実行
lastSelect();//末尾を選択
editorPane.replaceSelection("\n");
switch(this.sortMethod){
case バブル:
Bubble.bubbleSort(this.array, this.array.length);
break;
case クイック:
Quick.quick_sort(this.array);
break;
case マージ:
Merge.merge_sort(this.array);
break;
}
editorPane.replaceSelection("以上で終了\n");
printArray(this.array);
}
static void println(int[] array)
{// ----標準出力で確認-------------
for (int i = 0; i <array.length; i++)
{
String s = String.format("%" + 5 + "d", array[i]);
System.out.print(s);
}
System.out.println();
}
//--------バブルソート クラス-----------------------------
static class Bubble {
static void swap(int[] a, int i1, int i2)
{
int t = a[i1];
a[i1] = a[i2];
a[i2] = t;
}
static void bubbleSort(int[] a, int N)//バブルソート改良版
{
int idx = 0;
for (int i = 0; i < N - 1; /*i++*/)
{
int exchg = 0;
int k = 0;
for (k = N - 2; k >= i; k--)
{
if (a[k] > a[k + 1])
{
swap(a, k, k + 1);
exchg = 1;
idx = k;
}
}
if (exchg == 0) break;
if (idx == k) i++;
else i = idx;
printArray(a); println(a);//経過表示-----
}
}
}
//--------クイックソート クラス-----------------------------
static class Quick {
static void _swap(int[] array, int i1, int i2) throws Exception
{
int temp = array[i1];
array[i1] = array[i2];
array[i2] = temp;
Thread.sleep(1);
}
static void _quick_sort(int[] array, int left, int right)throws Exception
{
int l = left;
int r = right;
int x = array[ (l + r) /2 ];
do {
while (array[l] < x) l++;
while (array[r] > x) r--;
if (l <= r) _swap(array,l++, r--);
} while (l <= r);
if (left < r) _quick_sort(array,left, r);
if (l < right) _quick_sort(array,l, right);
printArray(array); println(array);//経過表示-----
}
static void quick_sort(int[] array)
{
try {
_quick_sort(array, 0, array.length - 1);
}
catch (Exception e){
System.out.println(e.toString());
}
}
}
//--------マージソート クラス-----------------------------
static class Merge
{
static int []buff;
static void _merge_sort(int []a, int left , int right){
if(left < right){
int center = (left + right)/2;
_merge_sort(a, left, center);
_merge_sort(a, center+1, right);
int i;
for(i=left; i <= center; i++){//buffheへコピー
buff[i] = a[i];
}
//マージ
int k = left;
int j = left;
while(j <= center && i <= right){
if(buff[j] <= a[i]) a[k++] = buff[j++];
else a[k++] = a[i++];
}
//残りをコピー
if(j <= center) while(j <= center) a[k++] = buff[j++];
else while (i <= right) a[k++] = a[i++];
printArray(a); println(a);//経過表示-----
}
}
static void merge_sort(int []array){
buff = new int [array.length];
_merge_sort(array, 0, array.length -1);
}
}
}