在java中使用比较器自定义排序

时间:2016-05-24 06:45:11

标签: java collections

一旦我办公室的一位建筑师告诉我,比较器与同类产品之间存在差异;比较器在两个不同的类对象之间进行比较,在同一类中可比较。我有一个班级实习生和另一个学生班级。我想同时对学生和实习班内的名字进行排序。学生名字很少,实习生名字很少。想要按自然顺序对所有这些名称进行排序。这有可能实现吗?下面是我的错误代码。

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    //OkHttpClient client;
    String serverUrl = "http://192.168.0.102:8080/ocr-file-upload";
    String imgUrl;
    String TAG = "MainAcivity";
    TextView tvMain;
    File uploadFile1;
    String charset = "UTF-8";
    Button btn_make_request;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn_make_request = (Button) findViewById(R.id.btn_make_request);
        tvMain = (TextView) findViewById(R.id.tv_main);
       // client = new OkHttpClient();
        imgUrl = Environment
                .getExternalStorageDirectory().toString()+"/ocr_test.png";
        uploadFile1 = new File(imgUrl);




        btn_make_request.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(isStoragePermissionGranted())
                    new UploadImage().execute();
                else
                    Toast.makeText(MainActivity.this, "PERMISSION PROBLEM", Toast.LENGTH_SHORT).show();


            }
        });



    }//edn oncreate

    private class UploadImage extends AsyncTask<String, Void, String> {


        @Override
        protected String doInBackground(String... strings) {
            Log.v(TAG, "IN DO IN BACKGROUND");
            //   upload(serverUrl);
             doMultipartOcr();
            //doRequest();
            return null;
        }
    }


    public void doMultipartOcr(){
        try {
            MultipartUtility multipart = new MultipartUtility(serverUrl, charset);
           // multipart.addHeaderField("Content-Type", "multipart/related");
           // multipart.addHeaderField("boundary=", "---BOUNDARY");
            multipart.addFormField();
            multipart.addFilePart("fileUpload", uploadFile1);
            List<String> response = multipart.finish();
            for (String line : response) {
                //TODO: display Output
                tvMain.setText(tvMain.getText() + "\n" + line);
            }
        } catch (IOException ex) {
            //TODO: display error
            Log.v(TAG, ex.getMessage());
            ex.printStackTrace();
        }
    }

    public  boolean isStoragePermissionGranted() {
        if (Build.VERSION.SDK_INT >= 23) {
            if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    == PackageManager.PERMISSION_GRANTED) {
                Log.v(TAG,"Permission is granted");
                return true;
            } else {

                Log.v(TAG,"Permission is revoked");
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                return false;
            }
        }
        else { //permission is automatically granted on sdk<23 upon installation
            Log.v(TAG,"Permission is granted");
            return true;
        }


    }
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(grantResults[0]== PackageManager.PERMISSION_GRANTED){
            Log.v(TAG,"Permission: "+permissions[0]+ "was "+grantResults[0]);
            //resume tasks needing this permission
        }
    }


}

2 个答案:

答案 0 :(得分:1)

有一种肮脏的方式,这导致代码非常难以理解,并显示出糟糕的设计

public class NameComparator implements Comparator{

    @Override
    public int compare(Object o1, Object o2) {
        Student s1 = o1 instanceof Student ? (Student)o1 : null;
        Student s2 = o2 instanceof Student ? (Student)o2 : null;
        Trainee t1 = o1 instanceof Trainee ? (Trainee)o1 : null;
        Trainee t2 = o2 instanceof Trainee ? (Trainee)o2 : null;
        String st1 = s1 != null ? s1.empName; t1 != null ? t1.studName; null;
        String st2 = s2 != null ? s2.empName; t2 != null ? t2.studName; null;
        return st1 != null ? st1.compareTo(st2): 0;
    }

}

更好的选择是在层次结构中使用通用接口或对象,并从该公共对象派生您的学生和受训者。

答案 1 :(得分:0)

我怀疑你需要一个比较器。默认情况下,字符串将按自然顺序排序。

list = Collections.sort(list);
list2 = Collections.sort(list2);

应该给你你想要的东西。

你写的比较器毫无意义,不会编译。两个参数必须属于同一类。它用于命令单个列表而不是彼此相关的列表。

Collections.sort(Student, new Comparator<Trainee>() {

应该是

Collections.sort(list2 , new Comparator<Trainee>() {

那就是你用我给你的比较方法来说明我的受训者名单。

您不会对课程实习生进行排序,您可以对实习生的实例进行排序。